2014-03-31 31 views
1

我試圖解析一些JSON格式的文本,但我不太清楚如何處理動態對象名稱。我一直在網上尋找,並從我可以告訴這是在java中稱爲字典或MAP,但我無法完全弄清楚如何處理動態長度。解析JSON數組中的對象的動態數量

我已經使用http://jsonlint.com/驗證了我的JSON,我解析的代碼如下。

{ 
"0": { 
    "animal_name": "Yoshi", 
    "animal_type": "Day Gecko", 
    "animal_id": "1" 
}, 
"1": { 
    "animal_name": "Wigglesworth", 
    "animal_type": "Bearded Dragon", 
    "animal_id": "2" 
}, 
"command": "login", 
"owner_id": "1" 

}

有在是靜態的開始幾個細節,然後將動物返回,和動物的數量是動態的。

我可以提取第一部分(命令和Owner_ID),我可以單獨提取動物,但我不知道如何循環通過動物數組。我不知道那裏有多少動物,如果我試圖動態地引用它們,它就會進行編譯。

這是我用來從對象中抓取動物的代碼,我只是努力使它變成動態的。 android json response key value, parsing

這與我在IOS中發佈的另一個問題非常相似,所以我的解決方案稍微更加開發,但還不夠完善。 Parse nested JSON code in IOS

//parse the JSON header 
JSONObject jo = new JSONObject(result); 

//extract the owner id from the login response 
owner_id=jo.getInt("owner_id"); 

//if the server throws an error, pass this back 
if (!jo.isNull("error")) 
{ 
    //store to global variable 
    server_response=jo.getString("error"); 
} 
else 
{ //we only look for animals if a valid owner has logged in 
    if (owner_id>0) 
    { //loop through the sub items. 
     //HELP PLEASE: THE x<=5 needs to change to loop to the number of dictionary items in the JSONObject JO 
     for(int x=0; x<=5; x++){ 
      //Extract each animal 
      //HELP PLEASE: The jo.getJSONObject needs to get a dynamic item, but if I put x in here, it doesnt compile 
      JSONObject animal = jo.getJSONObject("1"); 

      String animal_name = new String(); 
      String animal_type = new String(); 
      int animal_id = 0; 

      //try and extract pets 
      animal_name=animal.getString("animal_name"); 
      animal_type=animal.getString("animal_type"); 
      animal_id=animal.getInt("animal_id"); 

      //To Do: This code will overwrite each animal with the last. Need so store in an array. 
      //get shared preferences object 
      SharedPreferences prefs = a03_home_page.this.getSharedPreferences("my_app_name", Context.MODE_PRIVATE); 

      //store the data 
      prefs.edit().putString("animal_name", animal_name).commit(); 
      prefs.edit().putString("animal_type", animal_type).commit(); 
      prefs.edit().putInt("animal_id", animal_id).commit(); 

     } 
    } 
} 

回答

0

通常情況下,我會建議改變JSON使用數組。現在

{ 
"animals": [ 
    { 
    "animal_name": "Yoshi", 
    "animal_type": "Day Gecko", 
    "animal_id": "1" 
    }, 
    { 
    "animal_name": "Wigglesworth", 
    "animal_type": "Bearded Dragon", 
    "animal_id": "2" 
    }, {... more animals ...} 
], 
"command": "login", 
"owner_id": "1" 
} 

,你可以簡單地動物的動態號碼添加到JSONArray「動物」,並使用for-loopjsonArray.getJSONObject(i);

不過,如果你不能改變JSON個人用途迭代它,你可以遍歷鍵:

Iterator keys = json.keys(); 
while(keys.hasNext()){ 
    JSONObject animal = json.getJSONObject(keys.next()); 
    // do smth 
} 

這種方法的問題是,你必須要小心,「命令」和「owner_id」,因爲這是沒有JSON對象。所以你在while循環中需要更多的邏輯。

+0

嗨。迭代按鍵就像是一種享受。我已經發布了下面的代碼來幫助其他人閱讀此主題。 \t \t \t \t \t \t \t'animal_count = 0; int ServerObjectCount = 0; Iterator KeyLoop = jo.keys(); (KeyLoop。 while(KeyLoop。hasNext()) { KeyLoop.next(); \t \t \t \t \t \t ServerObjectCount ++; } \t \t \t \t \t \t \t //減去已知不被動物兩項\t \t \t \t \t ServerObjectCount = ServerObjectCount-2; –

+0

@尼克哈德曼好聽。那麼請隨時接受這個答案。 – Lovis

+1

感謝您的幫助。根據您的建議更改JSON不是一個選項,因爲這會使iOS版本代碼失效。 –

0

您需要使用:

Gson gson = new Gson(); 
    Object o = gson.fromJson(str, Object.class); 
    List keys = new ArrayList(); 
    Collection values = null; 
    if (o instanceof Map) { 
     Map map = (Map) o; 
     keys.addAll(map.keySet()); // collect keys at current level in hierarchy 
     values = map.values(); 
    } else if (o instanceof Collection) { 
     values = (Collection) o; 
    } 
    System.out.println(keys);// [CDG, ORY, LBG] 
    for (int i = 0; i < keys.size(); i++) { 
     System.out.println(keys.get(i)); 
    } 

在本link

0
String result=yourjsondata.toString(); 

首先看見分配你的JSON數組這樣

JSONArray jsar=new JSONArray(result); 

然後解析這樣

對象
for(int i=0;i<jsar.length;i++) 
{ 
JSONObject jsobj=new JSONObject(jsar[i]); 

String strcode=jsobj.get("code"); 

String strrate=jsobj.get("rate"); 

String strtitle=jsobj.get("title"); 

String strsubtitle=jsobj.get("subtitle"); 
}