-4

This is my JSON string,

{
"listmain":{ 
     "16":[{"brandid":"186"},{"brandid":"146"},{"brandid":"15"}],
     "17":[{"brandid":"1"}],
     "18":[{"brandid":"12"},{"brandid":"186"}],

           }
 }

I need to get values in "16","17","18" tag and add values and ids("16","17","18") to two ArrayList.

What i meant is, when we take "16", the following process should happen,

 List<String> lsubid = new ArrayList<String>();
 List<String> lbrandid = new ArrayList<String>();
 for(int i=0;i<number of elements in "16";i++) {
     lsubid.add("16");
     lbrandid.add("ith value in tag "16" ");
 }

finally the values in lsubid will be---> [16,16,16]

the values in lbrandid will be---> [186,146,15]

Can anyone please help me to complete this.

user3841250
  • 53
  • 1
  • 2
  • 6

1 Answers1

1

Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.

You can parse the JSON like this

JSONObject responseDataObj = new JSONObject(responseData);
JSONObject listMainObj = responseDataObj.getJSONObject("listmain");
Iterator keys = listMainObj.keys();
while(keys.hasNext()) {
   // loop to get the dynamic key
   String currentDynamicKey = (String)keys.next();
   //store key in an arraylist which is 16,17,...
   // get the value of the dynamic key
   JSONArray currentDynamicValue = listMainObj.getJSONArray(currentDynamicKey);
   int jsonrraySize = currentDynamicValue.length();
   if(jsonrraySize > 0) {
        for (int i = 0; i < jsonrraySize; i++) {
            JSONObject brandidObj = currentDynamicValue.getJSONObject(i);
            String brandid = brandidObj.getString("brandid");
            System.out.print("Brandid = " + brandid);
            //store brandid in an arraylist
        }                   
    }
}

Source of this answer

Community
  • 1
  • 1
Kaushik
  • 6,150
  • 5
  • 39
  • 54
  • Thank you sir, but i tried this but have got an Exception org.json.JSONException: JSONObject["brandid"] not found. – user3841250 Oct 22 '14 at 12:22
  • @user3841250: can u post `logcat` in ur question – Kaushik Oct 22 '14 at 12:35
  • got error in this line, String brandid = brandidObj.getString("brandid"); org.json.JSONException: JSONObject["brandid"] not found. at org.json.JSONObject.get(JSONObject.java:473) at org.json.JSONObject.getString(JSONObject.java:654) – user3841250 Oct 22 '14 at 12:40
  • Thanx alot sir it works, there was some problem with my database connection code. Now it works. :) – user3841250 Oct 22 '14 at 13:04