【发布时间】:2015-02-21 09:01:34
【问题描述】:
我对处理 JSON 比较陌生。但是已经成功地创建了一些返回我想要的类的类。然而,这个反应让我很困惑。
我已经查看并尝试了网站上的各种示例,以将我的 JSON 响应转换为一个类。但是,我继续遇到运行时错误。 任何关于我哪里出错的指示将不胜感激。
JSON 响应
{
"locationResponse": {
"locations": [
"E911AID:93a6:2db4:0589:261d,streetDir:NE,street:89th,zip:98052,city:Redmond,streetNameSuffix:St,name:Jonathon Doe,state:WA,houseNum:23619",
"E911AID:93a6:2db4:0589:261d,streetDir:NE,street:89th,zip:98052,city:Redmond,streetNameSuffix:St,name:Jon Doe,state:WA,houseNum:23619",
"ad1c:2dbf:fadf:2e87",
"E911AID:93a6:2db4:0589:261d,streetDir:NE,street:89th,zip:98052,city:Redmond,streetNameSuffix:St,name:John Doe,state:WA,houseNum:23619",
"E911AID:93a6:2db4:0589:261d,streetDir:NE,street:89th,zip:98052,city:Redmond,streetNameSuffix:St,name:JJ Doe,state:WA,houseNum:23619"
]
}
}
类定义
[Serializable]
public class locationResponseResponse
{
public locationResponse locationResponse { get; set; }
}
[Serializable]
public class locationResponse
{
public location[] locations { get; set; }
}
[Serializable]
public class location
{
public string E911AID { get; set; }
public string streetDir { get; set; }
public string street { get; set; }
public string zip { get; set; }
public string city { get; set; }
public string streetNameSuffix { get; set; }
public string name { get; set; }
public string state { get; set; }
public string houseNumber { get; set; }
}
反序列化代码段
public locationResponseResponse GetlocationResponseResponse(string jsonString)
{
locationResponseResponse _response = new locationResponseResponse();
if (!string.IsNullOrEmpty(jsonString))
{
JavaScriptSerializer ser = new JavaScriptSerializer();
_response = ser.Deserialize<locationResponseResponse>(jsonString);
}
return _response;
}
收到运行时错误
没有为BlackFlagAPI.locationResponse[] 类型定义无参数构造函数。
【问题讨论】:
-
考虑使用 Newtsoft.Json。它是最流行的 json 序列化器。
-
json 示例中的
locations 是字符串,而不是 json 对象。所以一个 json 反序列化器不能把它们变成你的location类。您需要为此注册一个自定义解析器。 -
下次发 json 时,请使用漂亮打印的 json。更容易看到正在发生的事情。
-
我修复了你的 JSON,这个工作正常:gist.github.com/cubrr/ac9b70961301193caf49
标签: c# .net json serialization javascriptserializer