JSON在Java Webservice中解析JSONObject中的多个JSONObject

时间:2014-10-22 11:30:15

标签: java android json

这是我的JSON字符串,

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

           }
 }

我需要在" 16"," 17"," 18"标记并向两个ArrayList添加值和ID(" 16"," 17"," 18")。

我的意思是, 当我们采取" 16"时,应该发生以下过​​程,

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

最后lsubid中的值将是---&gt; [16,16,16]

lbrandid中的值将是---&gt; [186,146,15]

任何人都可以帮我完成这个。

1 个答案:

答案 0 :(得分:1)

使用JSONObject keys()获取密钥,然后迭代每个密钥以获得动态值。

您可以像这样解析JSON

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