c# - 反序列化具有未知对象名称的 JSON

标签 c# json json.net

我正在尝试反序列化来自 API 的 JSON 响应。 JSON 看起来像这样(MAC 地址和位置已更改):

{
"body" : [{
        "_id" : "da:87:54:26:53:97",
        "place" : {
            "location" : [-23.334961, 47.398349],
            "altitude" : 30,
            "timezone" : "Europe\/London"
        },
        "mark" : 3,
        "measures" : {
            "f2:bf:a7:6f:e7:e8" : {
                "res" : {
                    "1469997248" : [20.4, 66]
                },
                "type" : ["temperature", "humidity"]
            },
            "42:b7:48:59:7c:4b" : {
                "res" : {
                    "1469997263" : [1016.7]
                },
                "type" : ["pressure"]
            }
        },
        "modules" : ["f2:bf:a7:6f:e7:e8"]
    }
],
"status" : "ok",
"time_exec" : 0.034152030944824,
"time_server" : 1469997417
}

问题是措施 block 。由于对象的名称正在更改,我不知道如何将其正确反序列化为 C# 对象。 I found a similiar problem on here with the solution to use a dictonary ,但是,如果我以这种方式尝试,我只会得到空目录。

这是我的反序列化方法:

APIResponse apiResponse = JsonConvert.DeserializeObject<APIResponse>(await content.ReadAsStringAsync());

这是 APIResponse 类:

public class APIResponse
{
    public Body[] body { get; set; }
    public string status { get; set; }
    public float time_exec { get; set; }
    public int time_server { get; set; }
}

public class Body
{
    public string _id { get; set; }
    public Place place { get; set; }
    public int mark { get; set; }
    public Measures measures { get; set; }
    public string[] modules { get; set; }
}

public class Place
{
    public float[] location { get; set; }
    public float altitude { get; set; }
    public string timezone { get; set; }
}

public class Measures
{
   public Dictionary<string, SingleModule> singlemodules{ get; set; }
}

public class SingleModule
{
    public Res res { get; set; }
    public string[] type { get; set; }
}

public class Res
{
    public MeasuredData measuredData { get; set; }
}
public class MeasuredData
{
    public float[] values { get; set; }
}

有什么方法可以轻松地正确反序列化这些措施?

最佳答案

看起来您应该能够摆脱Measures 类。相反,将字典直接放入您的 Body 类中:

public class Body
{
    public string _id { get; set; }
    public Place place { get; set; }
    public int mark { get; set; }
    public Dictionary<string, SingleModule> measures { get; set; }
    public string[] modules { get; set; }
}

另外,我强烈建议您的属性遵循 .NET 命名约定,并使用 [JsonProperty("measures")] 等向 Json.NET 指示如何翻译您的属性将属性转换为 JSON。

关于c# - 反序列化具有未知对象名称的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38688570/

相关文章:

c# - 如何从 C# 方法返回 Json 对象

c# - 可以编译为 DLL 并可以在 Linux Web 服务器后端使用的现代语言?

c# - Linq 连接两个值

javascript - 将 JSON 数据上传为文件

java - 自定义 block 不可冶炼? Java,Minecraft Forge 1.12.2

c# - 反序列化子类中的匿名顶级数组

c# - 两个不同的随机数生成器给出相同的答案?

c# - ASP.net Repeater 获取当前索引、指针或计数器

jquery - 加载 ASP.Net MVC JSONResult jQuery 数据表

javascript - 数据绑定(bind) : 'System.String' does not contain a property with the name 'numeroGuia'