Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a JSON string as a command line argument

Tags:

json

c#

I am trying to pass a json string to a C#-Program using Commandline.

The JSON-String looks like this:

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

In Commandline 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 then it gets chunked into several pieces. But I want my program to see it as just a single string.

Do I have to adapt my JSON-String?

like image 572
Snickbrack Avatar asked Mar 24 '16 15:03

Snickbrack


2 Answers

Declare it as a string with "" and escape 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\"}}}"
like image 189
Simon Karlsson Avatar answered Oct 10 '22 03:10

Simon Karlsson


This should work:

var jsonString = Environment.CommandLine;

I tested it with the debugger like so:

        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);

Debugging with VS2015, and not modifying the json input (not even removing the line changes). I am using the same structure as your input:

    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; }
    }

About (*) => The problem with the deserialization is that the exe info is added in front of the command line with Environment.CommandLine and it "pollutes" the json like this: 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"
        }
    }
}

If anybody has a prettier fix to this problem please let me know.

like image 38
Xavier Peña Avatar answered Oct 10 '22 02:10

Xavier Peña