【问题标题】:JSON Parsing in Java Webservice of multiple JSONObjects in JSONObjectJSONObject中多个JSONObjects的Java Webservice中的JSON解析
【发布时间】:2014-10-22 11:30:15
【问题描述】:

这是我的 JSON 字符串,

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

           }
 }

我需要获取 "16","17","18" 标签中的值,并将值和 ids("16","17","18") 添加到两个 ArrayList。

我的意思是, 当我们取“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 中的值将是---> [16,16,16]

lbrandid 中的值将是---> [186,146,15]

谁能帮我完成这个。

【问题讨论】:

标签: java android json


【解决方案1】:

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

你可以像这样解析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

【讨论】:

  • 谢谢你,先生,但我试过了,但有一个异常 org.json.JSONException: JSONObject["brandid"] not found.
  • @user3841250: 你可以在你的问题中发布logcat
  • 这一行出错,String brandid = brandidObj.getString("brandid"); org.json.JSONException: JSONObject["brandid"] 未找到。在 org.json.JSONObject.get(JSONObject.java:473) 在 org.json.JSONObject.getString(JSONObject.java:654)
  • 非常感谢先生,它可以工作,我的数据库连接代码有问题。现在它起作用了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 2013-08-19
  • 2020-04-18
  • 1970-01-01
相关资源
最近更新 更多