当api返回值时,为什么我的JSON解析为空?
问题描述:
我正在尝试使用http://api.postcodes.io/postcodes/ JSON响应来获取邮政编码的经度和纬度。当api返回值时,为什么我的JSON解析为空?
如果我浏览到那个api +英国邮政编码,它会返回一个JSON字符串。然而,当我试图做到这一点,并用JSON.NET C#编程解析它时,我得到一个null,我不知道为什么,因为它似乎我遵循我在本网站其他地方看到的建议。
这是我的代码
string pCode = "postcode" //user entered value
string longitude;
string latitude;
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://api.postcodes.io/postcodes/" +pCode);
dynamic data = JObject.Parse(json);
longitude = data.longitude;
latitude = data.latitude;
}
但经度和纬度都返回null。
答
从服务响应来看,这些信息被包裹在结果对象:
http://api.postcodes.io/postcodes/W4%201TH
要获得值尝试类似:
...
longitude = data.result.longitude;
latitude = data.result.latitude;
...
+0
辉煌,谢谢。我没有发现结果:{}位。这已经解决了我的问题,非常感谢你。 (只要它让我接受!) – Dave
如果您在使用'JObject'你不”不需要使用'dynamic'。 – Dai
检查JSON字符串? – CodeCaster
@戴的感谢 - 这是我在这里看到的另一个例子。我会用什么? – Dave