0

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

Ronald
  • 1,083
  • 3
  • 13
  • 20
  • 4
    Possible duplicate of [Parse json string to find and element (key / value)](https://stackoverflow.com/questions/21678126/parse-json-string-to-find-and-element-key-value) – Ňɏssa Pøngjǣrdenlarp Jan 12 '18 at 23:44

3 Answers3

1

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

torsan
  • 401
  • 5
  • 14
0

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

enter image description here

Dan Dohotaru
  • 2,809
  • 19
  • 15
0

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

novac
  • 116
  • 8