Create a C# class project, add json.net package/reference to the project. Add the following class
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace NewtonExtensions
{
public static class Extensions
{
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}
}
}
Compile the above project. In the current project, add a reference to the project above. Where the extension method is to be used, add a using statement.
Underlying thing here is unless using an older Express version of Visual Studio we can easily share code between languages.
EDIT Here is the same as above as an extension method
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace NewtonExtensions
{
public static class Extensions
{
public static IEnumerable<JToken> AllChildren(this JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}
}
}
Example usage in vb.net where I use xml literal for the json string. You would read in the json as normally would say from a file etc.
The Imports NewtonExtensions is in a C# class project with a namespace of NewtonExtensions.
I show two methods to iterate data after using the language extension method.
Imports NewtonExtensions
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Dim jsonString As String =
<json>
{
"ADDRESS_MAP":{
"ADDRESS_LOCATION":{
"type":"separator",
"name":"Address",
"value":"",
"FieldID":40
},
"LOCATION":{
"type":"locations",
"name":"Location",
"keyword":{
"1":"LOCATION1"
},
"value":{
"1":"United States"
},
"FieldID":41
},
"FLOOR_NUMBER":{
"type":"number",
"name":"Floor Number",
"value":"0",
"FieldID":55
},
"self":{
"id":"2",
"name":"Address Map"
}
}
}
</json>.Value
Dim results As JObject = JObject.Parse(jsonString)
Console.WriteLine("Example 1")
For Each item As KeyValuePair(Of String, JToken) In results
Console.WriteLine(item.Key)
Dim test = item.Value.AllChildren
For Each subItem In test
Console.WriteLine(subItem)
Console.WriteLine()
Next
Next
Console.WriteLine(New String("-"c, 50))
Console.WriteLine("Example 2")
results.Cast(Of KeyValuePair(Of String, JToken)) _
.ToList.ForEach(
Sub(v)
Console.WriteLine(v.Key)
Console.WriteLine(v.Value)
End Sub)
End Sub
End Class