how to get json from passed string via command line c# - 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
Related
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.
Base64 string encoding contains +, / and = instead of A, B, C
I need to apply the following transformation to a string: convert the string in byte[] apply the sha256 function encode the result in base64 I wrote the following code: string codeRaw = "C0643778W.EUC06AG978W.EUFWELP2014-11-2153.50000GBP24.00000MWh/h10YCB-EUROPEU--12015-01-012015-01-31"; byte[] utiCodeByteArr = Encoding.UTF8.GetBytes(codeRaw); byte[] hashByteArr = new SHA256Managed().ComputeHash(utiCodeByteArr); string hash = Convert.ToBase64String(hashByteArr) It works, but the result is a little bit different from was I should get: the string contains the chars '+', '/' and '=' instead of 'A', 'B' and 'C'. "qWAIh1CgYAuvoRTGcvXKLBHC9UxRunSBRjRXlqhYh6gC" //expected result "qW+Ih1CgYAuvoRTGcvXKLBHC9UxRunS/RjRXlqhYh6g=" //got result I've solved with a replace string hash = Convert.ToBase64String(hashByteArr)?.Replace("+", "A")?.Replace("/", "B")?.Replace("=", "C"); There is a better way to get the right string without using the replaces? I don't like them. The manual with the requirements say: "The APIs used are the ones provided by .NET framework", but it doesn't contains the source code: maybe there is a way to get immediately the ABC chars, but I miss it. Thanks.
The provider sent me the source code: there was a replace as the one I did. They forgot to wrote that information in the manual.
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!
Build JSON Safely
I'm running a project that is returning dynamically build JSON. Recently I discovered that carriage returns, and double quotes the JSON string invalid (can't be loaded via an AJAX). I'm now replacing the parameter in question, removing any double quotes, and such, but I feel like I'm playing whack-a-mole. Is there a better way? In XML, for example, if I'm building a node, I can just call setAttribute( strMyJunkyString ), and it safely creates an attribute that will never break the XML, even if it has special characters, entities, etc. Is there some sort of MakeStringJSONSafe() function, to remove anything that would break the array ([{}"\r\n])... Here's a couple examples of a broken strings that my program is creating... // String built with " included. var t1 = [{"requestcomment":"Please complete "Education Provided" for all Medications "}]; // String built with returns embedded included. var t2 = [{"requestcomment":"Please complete Education Provided History Allergies "}];
Use JSON.NET. var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(new { requestcomment = "Please complete \"Education Provided\" for all Medications" }); and... var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(new { requestcomment = "Please complete\nEducation Provided\nHistory\nAllergies" });
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"}]