使用未知对象名称反序列化JSON

Nir*_*usu 3 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
}
Run Code Online (Sandbox Code Playgroud)

问题是措施阻止.由于对象的名称正在改变,我不知道如何将其正确地反序列化为C#对象.我在这里找到了一个类似的问题,使用dictonary的解决方案,但是如果我这样尝试,我只是得到null目录.

这是我的反序列化方法:

APIResponse apiResponse = JsonConvert.DeserializeObject<APIResponse>(await content.ReadAsStringAsync());
Run Code Online (Sandbox Code Playgroud)

这是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; }
}
Run Code Online (Sandbox Code Playgroud)

什么方法可以轻松地对措施进行适当的解除武装?

Jon*_*eet 14

看起来你应该能够摆脱你的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; }
}
Run Code Online (Sandbox Code Playgroud)

作为一个单独的问题,我强烈建议遵循您的属性的.NET命名约定,并使用[JsonProperty("measures")]etc向Json.NET指示如何将您的属性转换为JSON.