1

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();

        }
    }
}
0

3 Answers 3

0

Normally, I would recommend changing the JSON to use an Array.

{
"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"
}

Now, you could simply add the dynamic number of animals to the JSONArray "animals" and iterate over it using a for-loop and jsonArray.getJSONObject(i);

However, if you can't change the json to your purposes, you can iterate over the keys:

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

the problem with this approach is, that you have to be careful with "command" and "owner_id", since that are no json objects. So you need some more logic in the while loop.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi. Iterating over the keys worked like a treat. I've posted the code below to help anyone else reading this thread. `animal_count=0; int ServerObjectCount=0; Iterator KeyLoop = jo.keys(); while(KeyLoop.hasNext()) { KeyLoop.next(); ServerObjectCount++; } //subtract the two items which are known not to be animals ServerObjectCount=ServerObjectCount-2;
@NickHardman good to hear that. Feel free to accept this as the answer, then.
Thanks for your help. Changing the JSON as per your suggestion wasnt an option as this would have invalidated the iOS version code.
0

You need to use :

 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));
    }

As seen in this link

Comments

0
String result=yourjsondata.toString();  

First assign your json array like this

JSONArray jsar=new JSONArray(result);

then parse objects like this

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.