Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Parse Json children in VB.NET Newtonsoft

I am having touble parsing Json using VB.NET using the Newtonsoft Json.Net library

    Json Data
    ---------
    {
        "CC": "[email protected]",
        "CcFull": [
            {
                "Email": "[email protected]",
                "Name": "John Sample"
            },
            {
                "Email": "[email protected]",
                "Name": "Mike Sample"
            }
        ],
        "FromFull" : {
            "Email": "[email protected]",
            "Name": "John Doe"
         }
    }

I can get a valid JObject thus:

    Dim o As JObject = JObject.Parse(strJson)

Then I can get list of a JTokens and iterate through them and easily get the root item values - but how get the Child records for CcFull?

    Dim results As List(Of JToken) = o.Children().ToList
    For Each item As JProperty In results
        item.CreateReader()
        Select Case item.Name
            Case "CC"
                dim strCC = item.Value.ToString
            Case "CcFull"
                'This has children (Email and Name)

        End Select
     Next 

It seems like I might be able to use a JArray or parse the item.value - but the syntax eludes me.

I don't want to setup a whole strongly typed model in VB and do an automatic deserialze - prefer more like the Dynamic way of doing it in C# - or preferably just iterate over n children for the CcFull node and pluck out the values for Email and Name and put them in a generic list.

Seems there are no good VB.NET examples on SO or by Googling.

C# has totally simple ways to do this - but I'm stuck in VB.NET for this project.

Thanks Folks

like image 632
Charlez Avatar asked Apr 12 '13 23:04

Charlez


1 Answers

I'm no expert on the Linq to JSON implementation in JSON.Net, but this worked for me.

You're pretty much all the way there. All you need to do is drill down a little further in the object model.

Dim results As List(Of JToken) = o.Children().ToList
For Each item As JProperty In results
    item.CreateReader()
    Select Case item.Name
        Case "CC"
            Dim strCC = item.Value.ToString
        Case "CcFull"
            Dim strEmail As String
            Dim strName As String

            For Each subitem As JObject In item.Values
                strEmail = subitem("Email")
                strName = subitem("Name")
            Next
    End Select
Next

The item that you get from the results list has sub-items, as you noted. That sub item has a series of values - the array denoted by the brackets in your JSON string. That Values method is an IEnumerable so we can iterate over it, receiving a JObject from each iteration. That object represents a single entry in the CcFull array. You can then use the property name as an index to retrieve the value for that property.

like image 145
Bob Mc Avatar answered Sep 28 '22 15:09

Bob Mc