在 C# 中使用动态键反序列化 json

deserialize json with dynamic keys in C#

我想反序列化 web 服务的结果有多个带有动态键的内部对象。 有结果模板:

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

示例:

{
    "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,
        }
    },
}

如何将此 json 反序列化为包含每个国家/地区的服务和价格的国家/地区列表?

编辑 1: 我被选中 this question 但我的 json 是具有完全动态键的多内部对象。

您可以将其反序列化为字典,根本不需要 类

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

但是如果你想把它转换成列表,试试这个

    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();


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; }
}

结果

[
  {
    "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
          }
        ]
      }
    ]
  }
]