I'm trying to Parse some JSON formatted text, but i'm not quite sure how to handle a dynamic object name. I've been looking around on the web, and from what I can tell this is referred to as a dictionary or a MAP in java, however I cant quite figure out how to handle the dynamic length.
I've validated my JSON using http://jsonlint.com/, the code I am parsing is below.
{
"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"
}
There are a few details at the start which is static, then animals are returned, and the number of animals is dynamic.
I can extract the first part (Command and Owner_ID), and I can extract the animals individually, but i'm not sure how to loop through the array of animals. I dont know how many animals there are, and if I try to refer to them dynamically it doenst compile.
This is the code I have used to grab animals from the object, I'm just struggling to make it dynamic. android json response key value, parsing
This is quite similar to another question I posted in IOS, so my solution is a little more developed but still not quite there. 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();
}
}
}