2012-03-20 97 views
6

我需要作爲字符串訪問所有包含在一個複雜的Json中的單個參數。從json中獲取字符串與嵌套的json對象和嵌套的json數組與多個json對象,在Android中

例如String people=...; String idPeople=...;

我曾嘗試使用JSONTokeners,因爲我試圖尋找類似的問題,以及簡單的JSON我沒有問題,但我不知道怎麼弄的從這個正確的參數:

{"id":1,"error":null,"result": 
    {"nPeople":2, 
    "people":[ 
      {"namePeople":"Inca", 
      "power":"1235", 
      "location":"asdfghjja", 
      "idPeople":189, 
      "mainItems":"brownGem", 
      "verified":false, 
      "description":"Lorem impsum bla bla", 
      "linkAvatar":"avatar_12.jpg", 
      "longitude":16.2434263, 
      "latitude":89.355118}, 

      {"namePeople":"Maya", 
      "power":"1235", 
      "location":"hcjkjhljhl", 
      "idPeople":119, 
      "mainItems":"greenstone", 
      "verified":false, 
      "description":"Lorem impsum bla bla", 
      "linkAvatar":"avatar_6.jpg", 
      "longitude":16.2434263, 
      "latitude":89.3551185}] 
    } 
} 

NB中數組對象的人的數量並不總是2 ...和5包含4個或更多的人反對

回答

19

我還沒試過。 但我想它可能會工作。

JSONObject obj = new JSONObject(jsonString); 
    String id = obj.getString("id"); 
    String error = obj.getString("error"); 
    JSONObject result = obj.getJSONObject("result"); 
    int nPeople = result.getInt("nPeople"); 
    JSONArray people = result.getJSONArray("people"); 
    for(int i = 0 ; i < people.length() ; i++){ 
     JSONObject p = (JSONObject)people.get(i); 
     String namePeople = p.getString("namePeople"); 
     ... 
    } 
+0

這讓我瘋狂。在objective-c之後,我在Android開發中涉足並且無法解決這個問題。謝謝! – 2012-06-03 11:04:59

+0

這個答案中有更多問題的答案。感謝名單 – Sayka 2015-09-16 16:23:17

2

,如果我們所說的JSON您發佈myJsonString,

JSonObject obj = new JSonObject(myJsonString); 
JSonObject result = obj.getJSONObject("result"); 
JSonArray people = result.getJSONArray("people"); 
int numOfPeople = result.getInt("nPeople");