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?
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\"}}}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With