s15199d s15199d - 3 years ago 183
JSON Question

Looping through JSON with NewtonSoft

There are over 6,300 messages in my JSON file. My JSON is formatted like so...

{ "messages":[
"id": ...

I'm trying to loop through each message in this JSON file using NewtonSoft using this code...

Dim jObj As JObject = JObject.Parse(File.ReadAllText(outputJSONpath & "myFileName.json"))
Dim jArr As New JArray(jObj("messages"))
For Each message As JObject In jArr.Children(Of JObject)()
'Do work

When I do a
jArr.Children(Of JObject)().Count
I get 0. I would expect to see the count at 6,300. When in the immediate window I see a valid object for jObj and jArr. I've successfully used code very similar to this before, but I can't figure out what's wrong here. I verified my JSON is valid at jsonlint.com thinking maybe I had corrupt JSON. Any ideas?

Answer Source

As messages is a JArray you just need to cast it:

Dim jArr As JArray = CType(jObj("messages"), JArray)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download