使用可更改密钥反序列化 JSON

本文关键字:反序列化 JSON 密钥 可更改 | 更新日期: 2023-09-27 18:37:28

我有这个 JSON:

{
    "data":
        {
            "110714":{"periphery_id":108},
            "110715":{"periphery_id":102},
            "110710":{"periphery_id":107}
        }
}

以及描述它的类:

public class Info
{
    [JsonProperty("periphery_id")]
    public int PeripheryId { get; set; }
}
public class Data
{
    [JsonProperty(//what should be here as i have keys like 110710,110715,110714)]
    public Info Info { get; set; }
}
public class Structure
{
    [JsonProperty("data")]
    public Data Data { get; set; }
}

如何用一个类来描述这些对象?

"110714":{"periphery_id":108},
"110715":{"periphery_id":102},
"110710":{"periphery_id":107}

我知道 JSON 中所有数字键的值,因为我在服务器请求中发送它们。

API 服务器是外部的,无法修改 JSON 结构

使用可更改密钥反序列化 JSON

由于数据中的值具有更改键,因此您可以使用字典将其映射到,因此数据不是具有 Info 对象,而是具有一个Dictionary<int, Info>,您可以从中访问值

正如 Gronex 建议的那样,使用 Dictionary。但是要使其工作,您需要通过继承 JsonConverter 并覆盖 ReadJson 方法来实现自定义 json 转换器。