我試圖解析一些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();
}
}
}
嗨。迭代按鍵就像是一種享受。我已經發布了下面的代碼來幫助其他人閱讀此主題。 \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; –
@尼克哈德曼好聽。那麼請隨時接受這個答案。 – Lovis
感謝您的幫助。根據您的建議更改JSON不是一個選項,因爲這會使iOS版本代碼失效。 –