2017-01-25 40 views
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,並沒有得到錯誤,但這不會給我存儲在每個節點的數據。

+0

你解析無效JSON。不要試圖直接操縱JSON字符串。 – SLaks

+0

是遵循android中的json類文檔並查看一些示例如何完成。堆棧溢出本身有很多例子。 – denis

+0

我操縱它的原因是因爲完整返回的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}}]}}}}但是的,我絕對不應該操縱它 –

回答

0

這裏是你不變的JSON工作的版本:

public static void main(String... args) 
{ 
    String 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}}]}}}}"; 

    JSONObject obj = new JSONObject(json); 

    JSONObject data = obj.getJSONObject("data"); 
    JSONObject viewer = data.getJSONObject("viewer"); 
    JSONObject allMountains = viewer.getJSONObject("allMountains"); 

    // 'edges' is an array 
    JSONArray edges = allMountains.getJSONArray("edges"); 

    for (Object edge : edges) { 
     // each of the elements of the 'edge' array are objects 
     // with one property named 'node', so we need to extract that 
     JSONObject node = ((JSONObject) edge).getJSONObject("node"); 

     // then we can access the 'node' object's 'Name' property 
     System.out.println(node.getString("Name")); 
    } 
} 
+0

我使用substring()調用,因爲從服務器返回的原始json在結尾有額外的括號,所以子字符串將它們關閉 –

相關問題