我有这个特定的JSON响应,我试图反序列化但未成功。我希望有人能帮助我。
这是我得到的JSON响应:
{
"num_locations": 1,
"locations": {
"98765": {
"street1": "123 Fake Street",
"street2": "",
"city": "Lawrence",
"state": "Kansas",
"postal_code": "66044",
"s_status": "20",
"system_state": "Off"
}
}
}
我使用json2csharp http://json2csharp.com并获得了以下推荐的类:
public class __invalid_type__98765
{
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
public class Locations
{
public __invalid_type__98765 __invalid_name__98765 { get; set; }
}
public class RootObject
{
public int num_locations { get; set; }
public Locations locations { get; set; }
}
但是当我尝试在代码中使用它时:
var locationResponse = JsonConvert.DeserializeObject<RootObject>(response.Content);
我得到的是(观看):
locationResponse : {RestSharpConsoleApplication.Program.RootObject} : RestSharpConsoleApplication.Program.RootObject
locations : {RestSharpConsoleApplication.Program.Locations} : RestSharpConsoleApplication.Program.Locations
__invalid_name__98765 : null : RestSharpConsoleApplication.Program.__invalid_type__98765
num_locations : 1 : int
显然,我没有为DeserializeObject创建(json2csharp)正确的类,可惜我无法控制JSON响应(供应商= SimpliSafe)。
显而易见,“ 98765”是一个值(位置编号),但是json2csharp使其成为__invalid_type__98765类,这可能就是为什么它为null的原因。
知道这些类如何查找要成功反序列化的特定JSON吗?
谢谢!
扎克斯
最佳答案
您应该可以使用字典来做到这一点:
public class MyData{
[JsonProperty("locations")]
public Dictionary<string, Location> Locations {get;set;}
}
public class Location
{
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
关于c# - 反序列化此JSON响应到C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29376491/