Pass JSON string as command line argument

I am trying to pass json string to C # -Program using command line.

JSON-String looks like this:

{
    "config": {
        "script": {
            "script_name": "test",
            "dir": "D:\\test",
            "destination": "M:\\neu\\test",
            "params": "/b /s /r:3 /w:5"
        }
    }
}

On the command line, it looks like this:

{"config":{"script":{"script_name":"test","dir":"D:\\test","destination":"M:\\neu\\test","params":"/b /s /r:3 /w:5"}}}

But if I just pass the string, it will be split into several parts. But I want my program to treat it as one line.

Do I need to adapt my JSON-String?

+7
source share
6 answers

Declare it as a string with ""and exit the other "with \, and it should work.

Command line:

"{\"config\":{\"script\":{\"script_name\":\"test\",\"dir\":\"D:\\test\",\"destination\":\"M:\\neu\\test\",\"params\":\"/b /s /r:3 /w:5\"}}}"
+10
source

This should work:

var jsonString = Environment.CommandLine;

I tested it with a debugger as follows:

        var jsonString = Environment.CommandLine;
        // (*) This correction makes it work, although it is pretty ugly:
        jsonString = jsonString.Split(new string[] { ".exe\" " }, StringSplitOptions.None)[1];
        var obj =   Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonString);

VS2015 json ( ). , :

    public class Script
    {
        public string script_name { get; set; }
        public string dir { get; set; }
        public string destination { get; set; }
        public string @params { get; set; }
    }

    public class Config
    {
        public Script script { get; set; }
    }

    public class RootObject
    {
        public Config config { get; set; }
    }

(*) = > , exe Environment.CommandLine, "" json : jsonString=

"path\to\assembly\name.vshost.exe" {
    "config": {
        "script": {
            "script_name": "test",
            "dir": "D:\\test",
            "destination": "M:\\neu\\test",
            "params": "/b /s /r:3 /w:5"
        }
    }
}

- , , .

+4

JSON .

@Wildcard27: Windows, . JSON DTO, .

JSON , , .

    private string CreateTaskConfigurationFile(string taskName, EquipmentEventExtended eventData, string host)
        {
            List<Change> changes = new List<Change>
            {
                new Change(MailConstants.EventName,eventData.EventName),
                new Change(MailConstants.Deadline, eventData.DateTo.Value.ToShortDateString()),
                new Change(MailConstants.EventDetails, eventData.EventDetails),
                new Change(MailConstants.Link,$"{host}/Inventory/Details/{eventData.InventoryId}")
            };

            MailTaskModel mtm = new MailTaskModel
            {
                Body = MailConstants.UpdateTemplate(MailConstants.TaskMailTemplate, changes),
                Subject = "[Reminder] Upcoming Event needs your attention",
                ToAddress = "abcdef@gmail.com",
                IsHtml = true
            };
            var fileName = string.Format(@"E:\{0}.json", taskName);
            using (StreamWriter file = File.CreateText(fileName))
            {
                JsonSerializer js = new JsonSerializer();
                js.Serialize(file, mtm);
            }
            return fileName;
        }

:

static void Main(string[] args)
        {
            var configFilePath = args[0];
            var mailConfig = LoadConfigurationFile(configFilePath);
            MailManager manager = new MailManager(mailConfig.ToAddress, mailConfig.FromAddress,mailConfig.Subject, mailConfig.Body,mailConfig.IsHtml);
            manager.SendMail();
        }
        private static MailTaskModel LoadConfigurationFile(string configurationFilePath)
        {
            MailTaskModel mailConfig;
            using(var sr = new StreamReader(configurationFilePath))
            {
                string json = sr.ReadToEnd();
                mailConfig = JsonConvert.DeserializeObject<MailTaskModel>(json);
            }
            return mailConfig;
        }

-

ConsoleApplication.exe -yourFilePath

, .

+1

, "string [] args", Environment.CommandLine.

MSDN https://msdn.microsoft.com/en-us/library/system.environment.commandline.aspx

public static void Main() 
{
   Console.WriteLine();
   //  Invoke this sample with an arbitrary set of command line arguments.
   Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
}

// : //C: > env0 ARBITRARY TEXT //
//CommandLine: env0 ARBITRARY TEXT

+1

json catch . .

args[1].Replace("{","{\"").Replace(":","\":\"").Replace(",","\",\"").Replace("}","\"}");
+1

@Selcuk Gurals, :

args[1].Replace("{", "{\"").Replace(":", "\":\"").Replace(",", "\",\"").Replace("}", "\"}").Replace(":\"[", ":[").Replace(":\"{", ":{").Replace("https\":\"", "https:").Replace("http\":\"", "http:").Replace("\":\"9", ":9").Replace("}\",", "},").Replace("]\",", "],").Replace("}\"}", "}}");

This caters for things like built-in http / https and ports. My port number was in the area of ​​9000 ... So a regex solution would be better. But this improves the previous answer. Part of the value of the key / JSON value pair can also be:

  1. another json object
  2. list

"key": {}, ....
"key":[], ....
0
source

All Articles