user1164545
user1164545

Reputation: 139

how to parse json in vb.net

I have json: {'success':'1','return':[{'id':'32928888','datetime':'2014-03-25 02:49:21','price':'0.02800939','quantity':'0.26094649','total':'0.00730895','io':'Buy'},{'id':'32928884','datetime':'2014-03-25 02:49:18','price':'0.02800939','quantity':'0.09930853','total':'0.00278157','io':'Buy'},{'id':'32928850','datetime':'2014-03-25 02:48:49','price':'0.02800939','quantity':'0.00093585','total':'0.00002621','io':'Buy'},{'id':'32928848','datetime':'2014-03-25 02:48:48','price':'0.02800939','quantity':'0.23547262','total':'0.00659544','io':'Sell'},{'id':'32928698','datetime':'2014-03-25 02:47:42','price':'0.02800939','quantity':'0.25553470','total':'0.00715737','io':'Sell'},{'id':'32928540','datetime':'2014-03-25 02:47:05','price':'0.02800940','quantity':'0.00820048','total':'0.00022969','io':'Sell'}]}

and I use code:

Public Function parse_json(ByVal json As String) As Nullable
    Try
        Dim jResults As JObject = JObject.Parse(json)
        Dim results As List(Of JToken) = jResults.Children().ToList()

        For Each item As JProperty In results
            item.CreateReader()
            MsgBox(item.Value("id"))
            MsgBox(item.Value("datetime"))
        Next
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Function

But I get error saying: System.InvalidOperationException: Cannot access child value on Newtonsoft.Json.Linq.JValue. What am I doing wrong? I need to get all ids, prices and so on.

Upvotes: 0

Views: 1333

Answers (2)

kachun wong
kachun wong

Reputation: 1

I changed the codes which is tested working as:

Public Function parse_json(ByVal json As String) As Nullable
    Try
        Dim jResults As JObject = JObject.Parse(json)
        ' Dim results As List(Of JToken) = jResults.Children().ToList()
        Dim arrResult As JArray = jResults.GetValue("return")

        For Each item As JObject In arrResult
            'item.CreateReader()
            'MsgBox(item.Value("id"))
            'MsgBox(item.Value("datetime"))
            Dim strid As String = item.GetValue("id")
            Dim strdt As String = item.GetValue("datetime")
            Diagnostics.Debug.WriteLine("id: " & strid)
            Diagnostics.Debug.WriteLine("dt: " & strdt)
        Next
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Function

Upvotes: 0

onof
onof

Reputation: 17367

return is the child of the full object:

Dim results As JArray = jResults.GetValue("return");

Upvotes: 1

Related Questions