Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON string to a JSON Object in C# without writing extra object classes

I'm new to C# and I am building a WPF app. Right now I trying to figure out how I can parse a JSON string like this:

{
   "Name": "Apple", 
   "ExpiryDate": "2008-12-28T00:00:00","Price": 3.99, 
   "Sizes": ["Small","Medium","Large"]
}

into a JSON Object magically.

I did some search online and all the solutions requires writing an object class that has the same structure as the JSON string. The string above is just an example and the actually JSON response is much more complicated, so I don't want to write a huge class for it.

Is there a library that allows me to do something similar to these:

JsonObject jo = new JsonObject(JsonString);
string name = jo["Name"]; // And the name would have "Apple" as its value
like image 555
KField Avatar asked Dec 12 '22 04:12

KField


1 Answers

I'd recommend you use Json.NET as your JSON library. The following code creates a dynamic object that you can work with. magic is actually an instance of JObject in your example, by the way.

dynamic magic = JsonConvert.DeserializeObject(jsonStr);
string name1 = magic.Name;    // "Apple"
string name2 = magic["Name"]; // "Apple"
like image 176
Tim S. Avatar answered Feb 12 '23 10:02

Tim S.