此json来自google API的HTTP响应:
{
"results": [
{
"address_components": [
{
"long_name": "Europe",
"short_name": "Europe",
"types": [
"continent",
"establishment",
"natural_feature"
]
}
],
"formatted_address": "Europe",
"geometry": {
"bounds": {
"northeast": {
"lat": 82.1673907,
"lng": 74.3555001
},
"southwest": {
"lat": 34.5428,
"lng": -31.4647999
}
},
"location": {
"lat": 54.5259614,
"lng": 15.2551187
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 65,
"lng": 55
},
"southwest": {
"lat": 34,
"lng": -11
}
}
},
"place_id": "ChIJhdqtz4aI7UYRefD8s-aZ73I",
"types": [
"continent",
"establishment",
"natural_feature"
]
}
],
"status": "OK"
}
我构建了一个列表类:
public class geocode {
public class AddressComponent
{
public string long_name { get; set; }
public string short_name { get; set; }
public List<string> types { get; set; }
}
public class Northeast
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Southwest
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Bounds
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public class Location
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Northeast2
{
public int lat { get; set; }
public int lng { get; set; }
}
public class Southwest2
{
public int lat { get; set; }
public int lng { get; set; }
}
public class Viewport
{
public Northeast2 northeast { get; set; }
public Southwest2 southwest { get; set; }
}
public class Geometry
{
public Bounds bounds { get; set; }
public Location location { get; set; }
public string location_type { get; set; }
public Viewport viewport { get; set; }
}
public class Result
{
public List<AddressComponent> address_components { get; set; }
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public string place_id { get; set; }
public List<string> types { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
public string status { get; set; }
}
}
这是我得到的:
nombrePapa = nombrePapa.ToUpper();
var resultadoGeocoding = ggo.geocoding(nombrePapa);
//var result = JsonConvert.DeserializeObject<listas.geocode.Result>(resultadoGeocoding);
List<listas.geocode> lista = JsonConvert.DeserializeObject<List<listas.geocode>>(resultadoGeocoding);
但这种反序列化让我感到困惑:
无法将当前JSON对象(例如{&#34; name&#34;:&#34; value&#34;})反序列化为类型System.Collections.Generic.List`1 [Models.listas +地理编码]&#39;因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。
我错过了什么?
答案 0 :(得分:1)
错误告诉您的是,为了将您的JSON正确反序列化为List<listas.geocode>
,您需要使用JSON来表示数组。您为反序列化器提供的是一个对象,它有两个属性results
和status
。
我猜你用json2csharp来获取你的课程,因为你已经有了一个根对象的课程。你忘了用它
要反序列化您需要执行的操作:
var response = JsonConvert.DeserializeObject<RootObject>(resultadoGeocoding);
var lista = response.Results;
附加说明:对于status
,您可以使用字符串(最简单的选项),也可以使用详细here的枚举。