我调用一个 Weather API - 它返回 Json 响应。 我的 C# 代码-
Uri uri1 = new Uri(APIUrl);
WebRequest webRequest1 = WebRequest.Create(uri1);
WebResponse response1 = webRequest1.GetResponse();
StreamReader streamReader1 = new StreamReader(response1.GetResponseStream());
String responseData1 = streamReader1.ReadToEnd().ToString();
dynamic data1 = JObject.Parse(responseData1 )
我在调用 Parse 时遇到异常,如下所示 - Newtonsoft.Json.dll 中出现“Newtonsoft.Json.JsonReaderException”类型的未处理异常
附加信息:从 JsonReader 读取 JObject 时出错。当前 JsonReader 项不是对象:StartArray。路径 '',第 1 行,位置 1。
我的分析- responseData1 有 json 字符串作为-
responseData1="[{\"locationName\":\"Bangalore\",\"subLocationName\":null,\"gid\":\"43295\",\"subStateID\":null,\"subStateName\":null,\"stateID\":\"II\",\"stateName\":\"Indien\",\"latitude\":12.9667,\"longitude\":77.5833,\"altitude\":900,\"zip\":null}\n, {\"match\":\"yes\"}]"
如果我在 http://jsonlint.com/ 中检查这个 json - 它说有效的 json。
如果我直接在浏览器中点击我的 APIUrl- repose 在浏览器中如下-
[{"locationName":"Bangalore","subLocationName":null,"gid":"43295","subStateID":null,"subStateName":null,"stateID":"II","stateName":"Indien","latitude":12.9667,"longitude":77.5833,"altitude":900,"zip":null}, {"match":"yes"}]
我的目标是从上面的 json 中读取属性“gid”的值。 有人可以帮我吗? 谢谢!
最佳答案
当您应该使用 JArray 类时,您正在使用 JObject 类,因为您尝试解析的 JSON 是一个数组 - 而不是一个对象:
关于C# 无法从 API 调用读取 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37866408/