TheMajidz
TheMajidz

Reputation: 19

deserialize json with dynamic keys in C#

I wanna deserialize an result of webservice were have multiple inner objects with dynamic keys. there is results template :

{[
    {"Country1": {"Service1": {"Price1": Quantity}}},
    {"Country2": {"Service1": {"Price1": Quantity}}},
    {"Country3": {"Service1": {"Price1": Quantity}}}
]}

example :

{
    "USA": 
    {
        "telegram": 
        {
            "3.00": 45537,
            "3.03": 127,
            "3.31": 97
        },
        "WhatsApp": 
        {
            "10.00": 0,
            "23.00": 0
        }
    },
    "UK": 
    {
        "google": 
        {
            "3.00": 45537
        },
        "any": 
        {
            "10.00": 0,
        }
    },
}

how I can deserialize this json to list of countries with services and prices per country ?

EDIT 1: I was checked this question but my json is multi inner object with Totally dynamic keys.

Upvotes: 0

Views: 119

Answers (1)

Serge
Serge

Reputation: 43880

you can deserialize it to dictionary without any classes at all

var jsonDeserialized = JsonConvert.DeserializeObject<Dictionary<string, 
Dictionary<string, Dictionary<string, int>>>>(json);

but if you want to convert it to list, try this

    List<Country> services = jsonDeserialized.Select(j => new Country
    {
        Name = j.Key,
        Services = j.Value
        .Select(v => new Service
        {
        Name = v.Key,
        Prices = v.Value
        .Select(va => new PriceQuantity { Price = Convert.ToDouble(va.Key), Quantity = va.Value }).ToList()
        }).ToList()
    }).ToList();

classes


public class Country
{
    public string Name { get; set; }
    public List<Service> Services { get; set; }
}
public class Service
{
    public string Name { get; set; }
    public List<PriceQuantity> Prices { get; set; }
}
public class PriceQuantity
{
    public double Price { get; set; }
    public int Quantity { get; set; }
}

the result

[
  {
    "Name": "USA",
    "Services": [
      {
        "Name": "telegram",
        "Prices": [
          {
            "Price": 3.0,
            "Quantity": 45537
          },
          {
            "Price": 3.03,
            "Quantity": 127
          },
          {
            "Price": 3.31,
            "Quantity": 97
          }
        ]
      },
      {
        "Name": "WhatsApp",
        "Prices": [
          {
            "Price": 10.0,
            "Quantity": 0
          },
          {
            "Price": 23.0,
            "Quantity": 0
          }
        ]
      }
    ]
  },
  {
    "Name": "UK",
    "Services": [
      {
        "Name": "google",
        "Prices": [
          {
            "Price": 3.0,
            "Quantity": 45537
          }
        ]
      },
      {
        "Name": "any",
        "Prices": [
          {
            "Price": 10.0,
            "Quantity": 0
          }
        ]
      }
    ]
  }
]

Upvotes: 1

Related Questions