3
我試圖從API反序列化JSON響應。 JSON看起來像這樣(MAC地址和位置被改變):反序列化具有未知對象名稱的JSON
{
"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
}
問題是度量塊。由於該對象的名稱正在改變,我不知道如何正確地反序列化爲一個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; }
}
任何方式妥善容易derserialize措施?
namings被搞砸了,因爲它們是從JSON生成的,我還沒有真正編輯它們。 無論如何,這個解決方案的工作原理。謝謝! – Niruga
嗯,我只是注意到,我有一個'res'的子對象的類似問題,它也有一個不斷變化的名字。我怎樣才能解決這個問題? – Niruga
@Niruga:同樣的方式 - 擺脫'Res'類,並使用一個'Dictionary'或一個'Dictionary >' –