Introduction
This is an easy short JSON recursion solution in VB.NET that handles full multilevel json response files to pull values from the name fields...
Background
I was looking and couldn't find what I needed so I put some time to this. It may not be the best solution yet. But I can continue to work on it. But it was better than most I found though searching on the web. So this is a great little solution to find a value that may be below a bunch on nodes below the root of a json string
.
Using the Code
Make sure you have the Newtonsoft.Json
installed via NuGet.
Create a new Class
in your project "JsonHelper
":
//
// vb.net Class Code.
//
Imports System.IO
Imports Newtonsoft.Json.Linq
Public Class JsonHelper
Private Shared output As String
Public Shared Function GetJson_
(res As String, txt As String, Optional Top As Integer = 0) As String
Dim ser As JObject = JObject.Parse(res)
Dim data() As JToken
Dim jT() As JToken
If Top = 0 Then
data = ser.Children().ToArray()
jT = data(0).First.ToArray()
Else
jT = ser.Children().ToArray()
End If
For Each itm As JProperty In jT
If itm.Name = txt Then
output = itm.Value.ToString
End If
If itm.Value.Type = JTokenType.Array Then
Dim str As String = itm.First.First.ToString
GetJson(str, txt, 1)
End If
If itm.Value.Type = JTokenType.Object Then
Dim str As String = itm.First.ToString
GetJson(str, txt, 1)
End If
Next
Return output
End Function
End Class
Given the following response returned from json:
Transaction complete
{
"transaction": {
"product": "CRUMP!",
"id": "1asdsadasdsadasdsadsada",
"location_id": "dfsdfsdfsdfsdfs",
"created_at": "2017-03-10T13:43:47Z",
"tenders": [
{
"type": "WOW",
"id": "sdfsdfsdfsdfsdfsdfsd",
"location_id": "fhghfghfghfghfghfghfgh",
"transaction_id": "sfsdfsdfsdfsdfsdfsdfsdf",
"created_at": "2017-03-10T13:43:47Z",
"something": {
"money": "CAD",
"value": 234324234
},
"card_details": {
"status": "DONE",
"entry_method": "ONLINE",
"DC": {
"card_brand": "THINKIT",
"last_4": "3232"
}
}
}
]
}
}
The Json is multilevel and getting to the child of the child of the child would be a pain and nobody wants to hardcode levels in. So given the JsonHelper
...
All you have to do in your VB.NET application:
Dim trasid As String = JsonHelper.GetJson(response, "transaction_id")
Pass the Json to the helper in string
format and request the feild name... and you will get the value returned no matter what level it's at.
History
- V1.0 - rbettinelli - 03-15-2017 - New post - 1st version up