-2

I'm having problems parsing and accessing to the data I want in the following example of json.

I want to retrive HeroName and HeroAmount for each record of items:

I know that I can serialize and behave as an array but I can't reach to the mentioned data.

{"id":"Main","name":"MAP","data":{},"children":
    [
        {
            "id":"ID_2317",
            "HeroName":"Name1322",
            "children":
            [
                {
                "id":"ID_23317_1",
                "name":"Name_1",
                "data":
                    {
                        "HeroAmount":231979
                    }
                }
            ]
        },
        {
            "id":"ID_2318",
            "HeroName":"Name1323",
            "children":
            [
                {
                "id":"ID_23318_1",
                "name":"Name_2",
                "data":
                    {
                        "HeroAmount":231977
                    }
                }
            ]
        }
    ]
}
Ali
  • 55
  • 4
  • learn more about dyamic objects so you will get some idea, the best way go with de-serialize and get your information - https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object – coder_b Dec 09 '20 at 23:17
  • "having problems" and "can't" means what, precisely? What exactly have you tried so far? Please post your attempt at writing the necessary code and explain the specific problem. – ADyson Dec 09 '20 at 23:32
  • "I know that I can serialize"...I assume you mean **de**serialize – ADyson Dec 09 '20 at 23:32
  • 1
    Paste your JSON here: [QuickType](https://quicktype.io/), you'll get a .Net class structure (model) that describes the JSON. It will probably generate two `data` class objects, since the `data` object in the Root is undefined. Modify as required. Follow the sample code that the online service generates to deserialize that JSON. Post back if you get stuck somewhere. You need to post your code, too. – Jimi Dec 09 '20 at 23:33

1 Answers1

0

You can do this:

   Dim strBuf As String = File.ReadAllText("c:\test4\json5.txt")

    Dim jOb As JObject = JObject.Parse(strBuf)

    Dim MyChildren As JToken = jOb.SelectToken("children")

    For Each MyChild As JToken In MyChildren
        Debug.Print("Hero Name = " & MyChild.SelectToken("HeroName"))
        Debug.Print("Hero Amount = " & MyChild.SelectToken("children[0].data.HeroAmount"))

    Next

So, it quite simple to "walk" json.

So With this inside the loop:

Debug.Print("Hero Name   = " & MyChild.SelectToken("HeroName").ToString)
Debug.Print("Hero Amount = " & MyChild.SelectToken("children[0].data.HeroAmount").ToString)
Debug.Print("--")

Output:

Hero Name   = Name1322
Hero Amount = 231979
--
Hero Name   = Name1323
Hero Amount = 231977
--
Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51