Home > Software design >  How to Deserialize and Loop Json Array in VB.NET
How to Deserialize and Loop Json Array in VB.NET

Time:11-01

I have json as such

{
    "TNS-API-KEY": "ABCD134EFG456HIJK678LMNOP",
    "docno": "35829",
    "idtns": "abc12345",
    "action": "6",
    "reason": "test -test",
    "userid": "450",
    "data": [
        {
            "pr": "STAMP",
            "idpr": "7",
            "cost": {
                "13": {
                    "13": {
                        "costingid": "13",
                        "costid": "13",
                        "gpro": "BBN_MTR",
                        "dbp": "10000",
                        "ppn": "0"
                    }
                }
            }
        },
        {
            "pr": "123\/AB\/MIX\/07\/2022",
            "idpr": "17461",
            "cost": {
                "34876": {
                    "66194": {
                        "costingid": "34876",
                        "costid": "66194",
                        "gpro": "CCL",
                        "dbp": "1000000",
                        "ppn": "110000.00"
                    }
                },
                "34877": {
                    "66195": {
                        "costingid": "34877",
                        "costid": "66195",
                        "gpro": "TB",
                        "dbp": "2000000",
                        "ppn": "220000.00"
                        }
                    }
                }
           }
       ]
    }

I need to get these data from each PR in the array

  1. costingid
  2. costid
  3. gpro
  4. dbp
  5. ppn

So far I've manage to get until the data part using code like this

Dim jsonData As JObject = JObject.Parse(json)
Dim data As String = jsonData.SelectToken("data").ToString()
Dim jsonArray As JArray = JArray.Parse(jsonData.SelectToken("data").ToString)

For Each item As JObject In jsonArray
Dim pr As String = (item.SelectToken("pr").ToString)
Next

That snipped gives me the PR number, any idea how to get to the inside data?

CodePudding user response:

This is how you can get the values which you might want to dump in a list or something like that.

Dim prList As JArray = JObject.Parse(json)("data")
For Each pr As JObject In prList
    Dim prVal As String = pr("pr")
    For Each c As JProperty In pr("cost")
        Dim data As JObject = DirectCast(c.Value.First, JProperty).Value
        Dim costingId As String = data("costingid")
        Dim costid As String = data("costingid")
        Dim gpro As String = data("gpro")
        Dim dbp As String = data("dbp")
        Dim ppn As String = data("ppn")
    Next
Next
  • Related