Search code examples
c#recursionjson.net

Recursively through heavy nested JSON


So I am a bit stucked right now.

I want to go through a nested JObject with recursion

The json looks sth like that

"Name":"Bob",
"Place":{
    "Name":"New York",
    "Address":{
        "Name":"Elmstreet",
        "Number":13
    },
    "Country":"Calif"
}`

I want to store it in my Poco which looks sth like that

public class Variance
{
    public string PropertyName { get; set; }
    public IList<Variance> Children { get; set; }
}

Therefore I need a List to store all variances,

List<Variance> listOfAll = new List<Variance>();

What I've tried but it doesnt really work for me

Variance Recursively(List<JToken> jToken)
    {
        
        foreach (var token in jToken)
        {

            Variance variance = new Variance();
            variance.PropertyName = token.Path;
            if (token.Children().ToList().Count > 1)
                variance.Children.Add(Recursively(token.Children().ToList()));
            listOfAll.Add(variance);
            return variance;

        }
        return null;
    }

What I really want is that the list contain all variances and these variances should contain the children as a List

Currently the listofAll only contains 1 Variance (name) instead of two (name and place) place then should contain name address and Country. Then address should contain Name and number.


Solution

  • You could use just Propeties, like the following code :

    1 - Change Children type to List for using .AddRange() in Recursively method :

    public class Variance
    {
        public string PropertyName { get; set; }
        public List<Variance> Children { get; set; }
    }
    

    2 - Recursively method takes collection of properties and checks if the nested json is an object or not :

    static List<Variance> Recursively(IEnumerable<JProperty> jProperties)
    {
        List<Variance> listOfAll = new List<Variance>();
    
        foreach (JProperty jProperty in jProperties)
        {
            Variance variance = new Variance
            {
                PropertyName = jProperty.Path
            };
    
            if (jProperty.Value.Type == JTokenType.Object)
            {
                variance.Children = new List<Variance>();
                List<Variance> recuList = Recursively(((JObject)jProperty.Value).Properties());
                variance.Children.AddRange(recuList);
            }
    
            listOfAll.Add(variance);
        }
    
        return listOfAll;
    }
    

    3 - Call Recursively like :

    JObject jObject = JObject.Parse(json);
    List<Variance> result = Recursively(jObject.Properties());
    

    Note that, if you have nested json like an array, you might want to tweak the method.

    I hope you find this helpful.