Parse json string provided as input parameter for exe C# - c#

Hi I have an applicationn which i need to execute from run command:
D:\MyApplication.exe {\"mydllpath\":\"D:\\dll\",\"FilePath\":\"D:\\Input\\abc.doc\", \"Attribute\":\"word\"}
However, I am unable to extract the values in "mydllpath", "FilePath" and "Attribute", It shows errors while parsing.
error: Unexpected end of content while loading JObject. Path 'mydllpath', line 3, position 0.
code:
foreach (string arg in args)
{
var x = JObject.Parse(arg);
Any help would really be appreciated!

If escaping the JSON then you need to enclose it in a string
D:\MyApplication.exe "{\"mydllpath\":\"D:\dll\",\"FilePath\":\"D:\Input\abc.doc\", \"Attribute\":\"word\"}"
which will be received in the code as
{"mydllpath":"D:\dll", "FilePath":"D:\Input\abc.doc", "Attribute":"word"}
and allow for proper parsing.
var json = args[0];
var x = JObject.Parse(json);

Related

how to get json from passed string via command line c#

I'm doing that for a reason. This is what i need for the next step of my application. I'm creating Visual Studio Extension and i need that for communication between plugin and proj.
I pass json string as argument of command line in visual studio.
When i load that string from the console it's devoid of certain json characters, making it impossible to deserialize.
What i paste as arg to console is:
{"lastModifiedDate":"2020-07-13T08:06:01Z","model":{"softwareSystems":[{"containers":[{"components":[{"location":0,"relationships":[{"sourceId":9,"destinationId":11,"technology":"","id":14,"name":null,"description":"","tags":"Relationship","tagsList":[]}],"id":9,"name":"system1 container1 component1","description":"","tags":"Element,Component","tagsList":[]},{"location":0,"relationships":[{"sourceId":10,"destinationId":9,"technology":"","id":16,"name":null,"description":"","tags":"Relationship","tagsList":[]}],"id":10,"name":"system1 container1 component2","description":"","tags":"Element,Component","tagsList":[]}],"location":0,"relationships":[{"sourceId":5,"destinationId":8,"technology":"","id":13,"name":null,"description":"","tags":"Relationship","tagsList":[]}],"id":5,"name":"system1 container1","description":"","tags":"Element,Container","tagsList":[]},{"components":[{"location":0,"relationships":[],"id":11,"name":"system2 container1 component1","description":"","tags":"Element,Component","tagsList":[]}],"location":0,"relationships":[{"sourceId":6,"destinationId":5,"technology":"","id":15,"name":null,"description":"","tags":"Relationship","tagsList":[]}],"id":6,"name":"system1 container2","description":"","tags":"Element,Container","tagsList":[]}],"location":0,"relationships":[{"sourceId":2,"destinationId":4,"technology":"","id":12,"name":null,"description":"","tags":"Relationship","tagsList":[]},{"sourceId":2,"destinationId":7,"technology":"","id":20,"name":null,"description":"","tags":"Relationship","tagsList":[]}],"id":2,"name":"Software System1","description":"My software system.","tags":"Element,Software System","tagsList":[]},{"containers":[{"components":[],"location":0,"relationships":[{"sourceId":7,"destinationId":6,"technology":"","id":17,"name":null,"description":"","tags":"Relationship","tagsList":[]}],"id":7,"name":"system2 container2","description":"","tags":"Element,Container","tagsList":[]},{"components":[],"location":0,"relationships":[{"sourceId":8,"destinationId":7,"technology":"","id":21,"name":null,"description":"","tags":"Relationship","tagsList":[]}],"id":8,"name":"system2 container1","description":"","tags":"Element,Container","tagsList":[]}],"location":0,"relationships":[],"id":4,"name":"Software System2","description":"","tags":"Element,Software System","tagsList":[]}],"people":[{"location":0,"relationships":[{"sourceId":1,"destinationId":2,"technology":"","id":3,"name":null,"description":"Uses","tags":"Relationship,Synchronous","tagsList":[]},{"sourceId":1,"destinationId":9,"technology":"","id":18,"name":null,"description":"","tags":"Relationship","tagsList":[]},{"sourceId":1,"destinationId":5,"technology":"","id":19,"name":null,"description":"","tags":"Relationship","tagsList":[]}],"id":1,"name":"User","description":"A user of my software system.","tags":"Element,Person","tagsList":[]}],"lastId":0},"views":{"systemContextViews":[{"softwareSystemId":2,"description":"An example of a System Context diagram.","configuration":{"styles":null},"elements":[{"id":4,"x":305,"y":300},{"id":1,"x":1255,"y":-5},{"id":2,"x":1190,"y":935}],"relationships":[{"id":3},{"id":12}]}],"containerViews":[{"softwareSystemId":2,"description":"","elements":[{"id":5,"x":110,"y":215},{"id":6,"x":1875,"y":715}],"relationships":[{"id":15}]},{"softwareSystemId":4,"description":"","elements":[{"id":8,"x":175,"y":224},{"id":7,"x":1845,"y":720}],"relationships":[{"id":21}]}],"componentViews":[{"containerId":5,"description":"","elements":[{"id":9,"x":120,"y":80},{"id":10,"x":1880,"y":1105},{"id":11,"x":130,"y":1000},{"id":1,"x":1760,"y":120}],"relationships":[{"id":14},{"id":16},{"id":18}]}]},"id":0,"name":"Demo workspace","description":"A demo workspace.","tags":"ElementBase,Workspace","tagsList":[]}
and from the console i get
"{lastModifiedDate:2020-07-13T08:06:01Z,model:{softwareSystems:[{containers:[{components:[{location:0,relationships:[{sourceId:9,destinationId:11,technology:,id:14,name:null,description:,tags:Relationship,tagsList:[]}],id:9,name:system1 container1 component1,description:,tags:Element,Component,tagsList:[]},{location:0,relationships:[{sourceId:10,destinationId:9,technology:,id:16,name:null,description:,tags:Relationship,tagsList:[]}],id:10,name:system1 container1 component2,description:,tags:Element,Component,tagsList:[]}],location:0,relationships:[{sourceId:5,destinationId:8,technology:,id:13,name:null,description:,tags:Relationship,tagsList:[]}],id:5,name:system1 container1,description:,tags:Element,Container,tagsList:[]},{components:[{location:0,relationships:[],id:11,name:system2 container1 component1,description:,tags:Element,Component,tagsList:[]}],location:0,relationships:[{sourceId:6,destinationId:5,technology:,id:15,name:null,description:,tags:Relationship,tagsList:[]}],id:6,name:system1 container2,description:,tags:Element,Container,tagsList:[]}],location:0,relationships:[{sourceId:2,destinationId:4,technology:,id:12,name:null,description:,tags:Relationship,tagsList:[]},{sourceId:2,destinationId:7,technology:,id:20,name:null,description:,tags:Relationship,tagsList:[]}],id:2,name:Software System1,description:My software system.,tags:Element,Software System,tagsList:[]},{containers:[{components:[],location:0,relationships:[{sourceId:7,destinationId:6,technology:,id:17,name:null,description:,tags:Relationship,tagsList:[]}],id:7,name:system2 container2,description:,tags:Element,Container,tagsList:[]},{components:[],location:0,relationships:[{sourceId:8,destinationId:7,technology:,id:21,name:null,description:,tags:Relationship,tagsList:[]}],id:8,name:system2 container1,description:,tags:Element,Container,tagsList:[]}],location:0,relationships:[],id:4,name:Software System2,description:,tags:Element,Software System,tagsList:[]}],people:[{location:0,relationships:[{sourceId:1,destinationId:2,technology:,id:3,name:null,description:Uses,tags:Relationship,Synchronous,tagsList:[]},{sourceId:1,destinationId:9,technology:,id:18,name:null,description:,tags:Relationship,tagsList:[]},{sourceId:1,destinationId:5,technology:,id:19,name:null,description:,tags:Relationship,tagsList:[]}],id:1,name:User,description:A user of my software system.,tags:Element,Person,tagsList:[]}],lastId:0},views:{systemContextViews:[{softwareSystemId:2,description:An example of a System Context diagram.,configuration:{styles:null},elements:[{id:4,x:305,y:300},{id:1,x:1255,y:-5},{id:2,x:1190,y:935}],relationships:[{id:3},{id:12}]}],containerViews:[{softwareSystemId:2,description:,elements:[{id:5,x:110,y:215},{id:6,x:1875,y:715}],relationships:[{id:15}]},{softwareSystemId:4,description:,elements:[{id:8,x:175,y:224},{id:7,x:1845,y:720}],relationships:[{id:21}]}],componentViews:[{containerId:5,description:,elements:[{id:9,x:120,y:80},{id:10,x:1880,y:1105},{id:11,x:130,y:1000},{id:1,x:1760,y:120}],relationships:[{id:14},{id:16},{id:18}]}]},id:0,name:Demo workspace,description:A demo workspace.,tags:ElementBase,Workspace,tagsList:[]}"
As you can see "{", double quotes are missing.
How i'm getting strings from console:
string[] commandLineArgs = Environment.GetCommandLineArgs();
I would need method which can convert to the same form because strings will be different
Do you know how to solve my problem?
c:\> myapp.exe "{\"asdf\":\"x yz\", \"xyz\": 3}"
worked for me (on Win10, can't test other versions right now).
Escape all doublequotes that belong to the JSON string with a \. Then enclose the whole json object with double-quotes to enclose the whitespaces, such that the string is not split upon multiple parameters.
EDIT
As an alternative, if you are in charge of creating and receiving the json string, you could use a more "CMD-friendly" format, for instance Base64. This way, you won't have to deal with spaces, quotes or other special characters on the command line
on the generating side:
var someobject = new {key1 = "value1", key2 = 3};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(someobject);
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
var base64 = System.Convert.ToBase64String(plainTextBytes);
// base64 will look something like
// eyJrZXkxIjogInZhbHVlMSIsICJrZXkyIjogM30=
// depending on the formatting of the serialization
then pass that base64 as parameter on your commandline.
C:\>someapp.exe eyJrZXkxIjogInZhbHVlMSIsICJrZXkyIjogM30=
And on the receiving side do
var base64 = Environment.GetCommandlineArgs()[1];
var base64EncodedBytes = System.Convert.FromBase64String(base64);
var json = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
var someObject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
to escape double quotation ("), use it twice. so when you pass "" to command it will received as ".
for example pass data as:
ConsoleAppTest.exe "{""lastModifiedDate"":""2020-07-13T08:06:01Z"",""model"":""softwareSystems""}"
please refer to following similar answers:
Escape double quotes in parameter

Line Separator ‘\u2028’ parse incorrect using json.net

static void Main(string[] args)
{
var newLineChar = Char.Parse("\u2028");
var jsonStr = #"{""value"":""some chars " + newLineChar + #"""}";
var jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonStr);
var jsonStrAfterParse = jObject.ToString(Newtonsoft.Json.Formatting.None);
}
I have a JSON string like:
"{\"value\":\"some chars \u2028\"}"
After I try to parse it using Newtonsoft.Json, I got the JSON:
"{\"value\":\"some chars \\u2028\"}"
The Line Separator char '\u2028' was parsed to '\\u2028'. I cannot make sure whether any other chars have the same issue. Can anyone help with this? Thanks.
Pic in immediate window
jsonStr in text visualizer
jsonStrAfterParse in text visualizer
In the comments you established that it's expected behavior, but I thought I'd go into why based on the source code.
Your input string is not valid JSON because of the unescaped control character \u2028, but NewtonSoft.Json is gracefully handling the bad input, and giving correct output of \\u2028 when you ask it to serialize for you.
For the deserialization, it doesn't care that you didn't escape it. It just goes ahead and includes it with your string. No biggie.
But when you ask it to serialize the string for you with .ToString(Newtonsoft.Json.Formatting.None)--which is a Newtonsoft extension method--its job is to give you valid JSON, and by golly, that's what it's going to do, giving you the \\u2028 you see.

Pass JSON string form one app to another app (Windows 8.1 Apps) C#

I'm using custom protocol to open another app from windows runtime app. I am using following code snippet:
await Launcher.LaunchUriAsync(new Uri("appb://hello"));
It works fine when there is plain string. But It gives parse error while passing a JSON string.
Invalid URI: The hostname could not be parsed.
I'm creating JSON by:
JObject jObj = new JObject();
jObj.Add("Name", "abcdef");
jObj.Add("Address", "acvdfs");
string json = jObj.ToString();
It gives JSON as:
{ "Name": "abcdef", "Address": "acvdfs" }
Your issue is because you're sending the entire json string to be created as a Uri.
You will need to get the required values out of the string first, and then pass those to your method.
As an example, let's say your
JObject jObj = new JObject();
jObj.Add("Name", "abcdef");
jObj.Add("Address", "acvdfs");
string json = jObj.ToString();
code will give you a "{Name}/{Address}" output - appb://abcdef/acvdfs
Instead of parsing that directly to a string, you will need to get the values out first.
Otherwise your
{ "Name": "abcdef", "Address": "acvdfs" }
is what is causing the
Invalid URI: The hostname could not be parsed.
error.
You could do this in order to retrieve the values from that string:
var values = jObj.Properties().Select(x => x.Value.ToString()).ToArray(); // Gives you an array of the values.
var path = string.Join("/", values); // Creates an "a/b" path by joining the array.
await Launcher.LaunchUriAsync(new Uri("appb://" + path)); // Give that path to create the Uri and pass to your method.
This code assumes you're only using the keys to create the path the way I have. It will work for any number of keys, as it just joins all the values together with "/" - e.g. a/b/c/d/e/f/g etc.
Any questions, just ask :)
Hope this helps!

Parsing a simple Json string

I have gotten a Json string to parse before that was an array of objects much longer than just a simple string, which makes me think that I'm doing something wrong with the formatting.
Here is word for word what our webservice is outputting as the json string:
{"news":"What is Legal/Awesome Dre"}
the first part is simply what I named the string in the application (news) and the second part is the string that will be changing as the song does which is why I would like to pull in a simple string of it.
When I run the app I'm getting a parse error at these lines:
Console.Out.Writeline (content);
news = JsonConvert.DeserializeObject(content);
The application output will show the Json string as it is on the website, but I get an error right after that's telling me Invalid Token: startPath... which last time meant that my Json string was formatted wrong for how I need to grab the data.
Anyone can help me with this?
(P.S. I am working in Xamarin Studio (mono for android) using C#, if that makes any difference)
The problem is that your serialized JSON object isn't a string, it's an object with the string value you want at the "news" property/key/name. This is a simple way to get the string:
dynamic jsonObj = JsonConvert.DeserializeObject(content);
string news = jsonObj.news;
Or you can use an anonymous type:
var jsonObj = JsonConvert.DeserializeAnonymousType(content, new { news = "" });
string news = jsonObj.news;
Or create a type with a string News property:
MyNewsType jsonObj = JsonConvert.DeserializeObject<MyNewsType>(content);
string news = jsonObj.News;
These all work in the following way:
var content = #"{""news"":""What is Legal/Awesome Dre""}";
// above code
Console.WriteLine(news); // prints "What is Legal/Awesome Dre"
Try to put square bracket in your JSON:
[{"news":"What is Legal/Awesome Dre"}]

Parsing JSON API in C#

so I'm fairly new to programming but am looking to go much deeper with it. I recently started to get involved in a project to create a WinForm program for a website that uses an API system in JSON.
I've never used an API before so I'm not quite sure how it works but after looking at it for a few minutes I seem to have the gist of it. What I don't get is how exactly parsing JSON in C# works.
I found
this link after a little google searching. And I got it working (somewhat) with this code.
static void Main(string[] args)
{
WebClient c = new WebClient();
var vLogin = c.DownloadString("https://www.openraid.us/index.php/api/login/username/password");
//Returns string
//{"status":1,"error":null,"token":"250-1336515541-c48d354d96e06d488d1a2530071ef07c9532da26"}
//Token = random, no decisive length*/
JObject o = JObject.Parse(vLogin);
Console.WriteLine("Login Status: " + o["status"]);
String sToken = "" + o["token"];
Console.WriteLine(sToken);
Console.WriteLine("");
//Breaks after this
var myRaids = c.DownloadString("https://www.openraid.us/index.php/api/myraids/"+sToken);
JObject r = JObject.Parse(myRaids); //error occurs here
String sEventId = "" + r["event_id"];
Console.WriteLine("Event ID: " + sEventId);
Console.ReadLine();
}
So to me it looks like I have parsing 1 page done and handled, but when I move onto the second I get this error.
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
So I guess my question is, how do I parse more than 1 page or call of JSON and what would be the easiest way to break up each section of the JSON object (Such as status, error, and token, into C# strings?
Did you try to JArray instead? Depending on what kind of object you are trying to return
WebClient client = new WebClient();
var data = client.DownloadString("");
var jArray = JArray.Parse(data);
JSON requires brackets for arrays and commas between multiple objects.
This is per the JSON standard. I also recommend using JSON.net via NuGet instead of the native JSON parser unless it is overkill and you cannot have the extra bloat.
For example, your parsing a file with two seperate JSON objects - the following does not work per the JSON standard (lacks a comma between the 2 objects and the two objects are not encapsulated by brackets):
{"status":1,"error":null}
{"status":2,"error":null}
The following 3 JSON objects parsed from a file does work (has brackets for multiple objects and commas between objects):
[{"glossary": {"title": "fun glossary","SeeAlso": ["GML", "XML"]},
{"glossary": {"title": "grey glossary","SeeAlso": ["GML", "XML"]},
{"glossary": {"title": "blue glossary","SeeAlso": ["GML", "XML"]}]
You can cut every JSON object(Array) into more object using for loops
the C# API is System.Json
var jsonArray = JsonArray.Parse(st);//st is the string which contain the JSON objects
foreach (var item in jsonArray) {
JsonObject ob = new JsonObject(item);
foreach (var t in ob.Values) {
JsonObject oo = new JsonObject(t);
foreach (var x in oo) {
textBox1.AppendText(x.Key + “ : ” + x.Value + “\n”);
}
}
}

Categories

Resources