Home Get specific json elements
Reply: 3

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#
torsan Reply to 2018-01-13 00:01:33Z

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<MyClass>(myString);

To access Symboljust use myObject.Data.Symbol

Dan Dohotaru
3#
Dan Dohotaru Reply to 2018-01-13 23:25:42Z

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

novaretti.jon
4#
novaretti.jon Reply to 2018-01-13 23:30:14Z

I recomend you to use Jil library, is faster and more simple than Newtonsoft.json

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.320119 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO