Collect all fields of JSON object C# with Example



Collect all fields of JSON object C# with Example

using Newtonsoft.Json.Linq; 
using System.Collections.Generic; 
public class JsonFieldsCollector 
{ 
private readonly Dictionary fields; 
public JsonFieldsCollector(JToken token) 
{ 
fields = new Dictionary(); 
CollectFields(token); 
} 
private void CollectFields(JToken jToken) 
{ 
switch (jToken.Type) 
{ 
case JTokenType.Object: 
foreach (var child in jToken.Children()) 
CollectFields(child); 
break; 
case JTokenType.Array: 
foreach (var child in jToken.Children()) 
CollectFields(child); 
break; 
case JTokenType.Property: 
CollectFields(((JProperty) jToken).Value); 
break; 
default: 
fields.Add(jToken.Path, (JValue)jToken); 
break; 
} 
} 
public IEnumerable> GetAllFields() => fields; 
} 
Usage: 
var json = JToken.Parse(/* JSON string */); 
var fieldsCollector = new JsonFieldsCollector(json); 
 

var fields = fieldsCollector.GetAllFields(); 
foreach (var field in fields) 
Console.WriteLine($"{field.Key}: '{field.Value}'"); 
Demo 
For this JSON object 
{ 
"User": "John", 
"Workdays": { 
"Monday": true, 
"Tuesday": true, 
"Friday": false 
}, 
"Age": 42 
} 
expected output will be: 
User: 'John' 
Workdays.Monday: 'True' 
Workdays.Tuesday: 'True' 
Workdays.Friday: 'False' 
Age: '42' 
 

0 Comment's

Comment Form

Submit Comment