我正在使用rest api从使用谷歌地图获取给定位置的地点列表但我遇到了一些问题。
主要问题:虽然大多数时候回复都是正常的,但有时我会得到格式错误的json或状态=" Not Ok"导致我的应用崩溃:
有没有办法测试状态&反序列化之前json的有效性,以防止崩溃或其他方式?
System.NullReferenceException: Object reference not set to an instance of an object.
从这一行:
place = JsonConvert.DeserializeObject<Places>(content,settings);
次要问题:我不确定处理返回的网页令牌的最佳方式是什么,以及如何将其用于重复查询
获取json的代码(try-catch什么都不做 - 应用程序仍然崩溃)
public async Task<Places> recurNearbyPlacesRequest(int radius , string pageToken)
{
HttpClient client = new HttpClient();
Places place = null;
string testurl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=45.498358,-73.4721847&radius=2000&pagetoken={0}&key={1}";
var uri = new Uri(string.Format(testurl, pageToken , Constants.google_maps_key));
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
place = JsonConvert.DeserializeObject<Places>(content,settings);
}
}
catch (Exception E) { }
return place;
}
导致崩溃的错误Json:
{
"error_message" : "The provided API key is invalid.",
"html_attributions" : [],
"results" : [],
"status" : "REQUEST_DENIED"
}
{
"html_attributions" : [],
"results" : [],
"status" : "INVALID_REQUEST"
}
地方类:
//JsontoC#
public class Location
{
public double lat { get; set; }
public double lng { 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 Viewport
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public class Geometry
{
public Location location { get; set; }
public Viewport viewport { get; set; }
}
public class OpeningHours
{
public bool open_now { get; set; }
public List<object> weekday_text { get; set; }
}
public class Photo
{
public int height { get; set; }
public List<string> html_attributions { get; set; }
public string photo_reference { get; set; }
public int width { get; set; }
}
public class Result
{
public Geometry geometry { get; set; }
public string icon { get; set; }
public string id { get; set; }
public string name { get; set; }
public OpeningHours opening_hours { get; set; }
public List<Photo> photos { get; set; }
public string place_id { get; set; }
public double rating { get; set; }
public string reference { get; set; }
public string scope { get; set; }
public List<string> types { get; set; }
public string vicinity { get; set; }
public int? price_level { get; set; }
}
public class RootObject
{
public List<object> html_attributions { get; set; }
public string next_page_token { get; set; }
public List<Result> results { get; set; }
public string status { get; set; }
}