0

My question is about a JSON file, of which I'm getting errors when putting certain values in a text component.

{
"response": {
    "game_count": 4,
    "games": [
        {
            "appid": 10,
            "playtime_forever": 0
        },
        {
            "appid": 20,
            "playtime_forever": 0
        },
        {
            "appid": 30,
            "playtime_forever": 0
        },
        {
            "appid": 40,
            "playtime_forever": 0
        }
    ]

   }
}

I'm trying to get the values "10,20,30,40" from "appid" in a RichTextBox, one below the other. For this, I am using this code:

JsonString = file

        Dim jsonObject As JObject = JObject.Parse(JsonString)
        Dim JsonArray As JArray = JArray.Parse(jsonObject.SelectToken("games").ToString)
        For Each item As JObject In JsonArray
            RichTextBox2.Text = item.SelectToken("appid").ToString

        Next

But I'm getting the following error in line 4 of the above code:

Object reference not set to an instance of an object

Is there a way to fix this? I believe my code is right. I'm using the NewtonSoft library.

toxdotnet
  • 31
  • 3

1 Answers1

1

You can use SelectTokens("..appid") to recursively descent the JSON token hierarchy and find values of properties named "appid", where ".." is the JSONPath recursive descent operator:

Dim jsonObject As JToken = JToken.Parse(JsonString)
Dim appids = jsonObject _ 
    .SelectTokens("..appid") _
    .Select(Function(t) CType(t, Long)) _
    .ToList()

After finding all "appid" values I cast then to Long using an explicit conversion cast. You could cast to Int If you are certain that all appid values will be less than Int.MaxValue. Or you could cast then to String if you're not interested in the numeric values.

Working .Net fiddle.

dbc
  • 104,963
  • 20
  • 228
  • 340