Search code examples
c#vb.netjson.net

Parse json using Newtonsoft


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
                    }
                }
            ]
        }
    ]
}

Solution

  • 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
    --