Search code examples
c#jsonjson-deserialization

Deserializing nested JSON array inside nested JSON object in c#?


I have a json file as follows:

{
  "container" : {
    "cans1" : 
    [
      {
        "name" : "sub",
        "ids" : 
        [
          "123"
        ]
      },
      {
        "name" : "Fav",
        "ids" : 
        [
          "1245","234"
        ]
      },
      {
        "name" : "test",
        "ids" : 
        [
          "DOC12","DOC1234"
        ]
      }
    ],
    "ids" : 
    [
      "1211","11123122"
    ],
"cans2" : 
    [
      {
        "name" : "sub1",
        "ids" : 
        [
          "123"
        ]
      }
     ],
     "ids" : 
    [
      "121","11123"
    ]

}

I want to fetch name values sub,fav,test and ids for each cans in this json file using c#


Solution

  • Install nuget Newtonsoft.Json. Create next hierarchy:

    using System;
    using System.Collections.Generic;
    
    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    
    public class MyClass
    {
        [JsonProperty("container")]
        public Container Container { get; set; }
    }
    
    public class Container
    {
        [JsonProperty("cans1")]
        public Cans[] Cans1 { get; set; }
    
        [JsonProperty("ids")]
        [JsonConverter(typeof(DecodeArrayConverter))]
        public long[] Ids { get; set; }
    
        [JsonProperty("cans2")]
        public Cans[] Cans2 { get; set; }
    }
    
    public class Cans
    {
        [JsonProperty("name")]
        public string Name { get; set; }
    
        [JsonProperty("ids")]
        public string[] Ids { get; set; }
    }
    

    And then

     JsonConvert.DeserializeObject<MyClass>(yourJsonString);
    

    UPD

    Based on comment, try this:

    var des = JsonConvert.DeserializeObject<MyClass>(t);
    
    foreach(var arr in des.Container.Where(r => r.Key.StartsWith("cans")))
    {
    
        Console.WriteLine($"{arr.Key}");
        foreach(var elem in arr.Value)
        {
            Console.WriteLine($"    {elem.Value<string>("name")}");
        }
    }
    
    public class MyClass
    {
        [JsonProperty("container")]
        public Dictionary<string, JArray> Container { get; set; }
    }