尝试解析:
[{"place_id":84979036,"licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright","powered_by":"Map Maker: https://maps.co","osm_type":"node","osm_id":8358755414,"boundingbox":["35.8497801","35.8897801","-114.6800654","-114.6400654"],"lat":"35.8697801","lon":"-114.6600654","display_name":"Willow Beach, Mohave County, Arizona, United States","class":"place","type":"village","importance":0.47500000000000003}]
但是边界框:声明中的[]导致了错误,我无法消除它们,所以我需要找到一种方法,在不出现此错误的情况下提取lat和lon。
错误:
Newtonsoft.Json.JsonReaderException: 'Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.'
代码:
bool PullGeoJson(string city, string state, out string[] output)
{
HttpResponse<string> response = UnirestLocationRequest(city, state);
Console.WriteLine(response.Body.ToString());
JObject json = JObject.Parse(response.Body.ToString());
output = new string[2];
output[0] = json.GetValue("lat").ToString();
output[1] = json.GetValue("lon").ToString();
return !(output == null);
}
创建一个包含预期响应结构的模型,然后反序列化为模型:
static void Main(string[] args)
{
string city = "Pense";
string state = "Canada";
HttpResponse<string> response = Unirest.get("https://geocode.maps.co/search?q=" + city + "," + state).asJson<string>();
var data = JsonConvert.DeserializeObject<List<GeoModel>>(response.Body.ToString());
}
public partial class GeoModel
{
[JsonProperty("place_id")]
public long PlaceId { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
[JsonProperty("lon")]
public string Lon { get; set; }
}