Home Get specific json elements

# Get specific json elements

Ronald
1#
Ronald Published in 2018-01-12 23:41:48Z
 I couln't find a similar case here, hence my question. I have a json like this: { "prop1": "bla", "propn": "bla", "Data": { "42": { "prop1": "bla", "prop2": "bla", "Symbol": "42" }, "abc": { "prop1": "bla", "prop2": "bla", "Symbol": "abc" } }, "Type": 100 }  Now, how do I get all elements from Data, and the most I am interested in the ones that have the symbol property set. I tried Newtonsoft.json.linq and jobject, but got really no clue what to do here. Any guidance anyone? Thanks! Ronald
torsan
2#
 What you're looking for is called 'deserialize'. You have a string (the json in you post) and you want to turn it into an object. The first steps you need to do are: Create a class that matches your data. Simply copy your json string in your post and use the option in Visual Studio to 'paste JSON as class'. Perhaps clean it up by changing the name RootObject to something more descriptive. Install the NuGet package Newtonsoft in Visual Studio. Now you can use MyClass myObject = JsonConvert.DeserializeObject(myString); To access Symboljust use myObject.Data.Symbol
 I imagine that once you extract partial data from json, if you still need to pass the data through your application, a dedicated model will come handy. public class Data { public Element abc { get; set; } } public class Element { public string prop1 { get; set; } public string prop2 { get; set; } public string Symbol { get; set; } }  While you certainly can rely on JObject handling the deserialization, i find it more intuitive to work with anonymous templates, especially for partial data retrieval. var template = new { Data = default(Data) }; var instance = JsonConvert.DeserializeAnonymousType(json, template);  will give you something like