0
當我嘗試獲取的價值爲「名」了以下JSON的我收到此錯誤值:org.json.JSONException:爲名稱JSON抽取錯誤
{
"edges": [
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
},
{
"node": {
"Name": "Sugarloaf Mountain",
"Latitude": 45.0314,
"Longitude": 70.3131
}
}
]
}
這其中的片段代碼我使用的嘗試和訪問這些值,但我只是測試獲得「姓名」現在:
String[] nodes = stringBuilder.toString().split("edges");
nodes[1] = "{" + "\"" + "edges" + nodes[1];
String s = nodes[1].substring(0,nodes[1].length()-3);
Log.d(TAG, s);
JSONObject json = new JSONObject(s);
JSONArray jsonArray = json.getJSONArray("edges");
ArrayList<String> allNames = new ArrayList<String>();
ArrayList<String> allLats = new ArrayList<String>();
ArrayList<String> allLongs = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
JSONObject node = jsonArray.getJSONObject(i);
Log.d(TAG, node.toString(1));
String name = node.getString("Name");
Log.d(TAG, name);
}
我的輸出是這樣的:
{"edges":[{"node":{"Name":"Sunday River","Latitude":44.4672,"Longitude":70.8472}},{"node":{"Name":"Sugarloaf Mountain","Latitude":45.0314,"Longitude":70.3131}}]}}
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
}
org.json.JSONException: No value for Name
據我所知,我可以使用optString,並沒有得到錯誤,但這不會給我存儲在每個節點的數據。
你解析無效JSON。不要試圖直接操縱JSON字符串。 – SLaks
是遵循android中的json類文檔並查看一些示例如何完成。堆棧溢出本身有很多例子。 – denis
我操縱它的原因是因爲完整返回的json看起來像這樣:{「data」:{「viewer」:{「allMountains」:{「edges」:[{「node」:{「Name」:「Sunday River 「Latitude」:44.4672,「Longitude」:70.8472}},{「node」:{「Name」:「Sugarloaf Mountain」,「Latitude」:45.0314,「Longitude」:70.3131}}]}}}}但是的,我絕對不應該操縱它 –