【问题标题】:How to get each element in List<JSONObject> json = new ArrayList<JSONObject>()如何获取 List<JSONObject> json = new ArrayList<JSONObject>() 中的每个元素
【发布时间】:2016-12-27 12:10:51
【问题描述】:

我需要像 ArrayList&lt;List&lt;String&gt;&gt;()

一样获取 ArrayList&lt;JSONObject&gt;() 中的值

对于ArrayList&lt;List&lt;String&gt;&gt;我使用了以下代码

for(List<String> dreport : report)  {
    for(String ddreport: dreport)   {
        // CODE GOES HERE
    }
}

在一个新的场景中,我需要使用该功能。但是该值包含在 ArrayList() 中,而不是字符串列表中

示例代码:

List<JSONObject> json = new ArrayList<JSONObject>();
JSONObject json_data1 = new JSONObject();
json_data1.put("count", "value");
json_data1.put("count", "value");
json_data1.put("count", "value");
json.add(json_data1);

【问题讨论】:

  • 否则,我可以将 ArrayList() 转换为 ArrayList>()
  • 您使用的是哪个 json 依赖项? json.org ?
  • 发布您的示例 json 字符串

标签: java json arraylist


【解决方案1】:
ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>();
//ADD objects in the jsonObjects

ArrayList<List<String>> jsonObjectsResultData = new ArrayList<>();
//Loop for the all JSONObject
for (JSONObject jsonObject : jsonObjects){
    Iterator<String> keys= jsonObject.keys();
    List<String> jsonObjectsValues = new ArrayList<String>();
    //Loop for the JSONObject keys and values
    while (keys.hasNext())
    {
        try{
            String keyValue = (String)keys.next();
            String valueString = jsonObject.getString(keyValue);
            jsonObjectsValues.add(valueString);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    jsonObjectsResultData.add(jsonObjectsValues);
}
//Your result array list
Log.i("RESULT DATA >>", jsonObjectsResultData.toString());

【讨论】:

    【解决方案2】:

    我在上面的答案中做了一些改动,这将使它占用更少的空间。我们不需要为键设置单独的迭代器。

    ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>();
    //ADD objects in the jsonObjects
    
    ArrayList<List<String>> jsonObjectsResultData = new ArrayList<>();
    //Loop for the all JSONObject
    for (JSONObject jsonObject : jsonObjects){
        String jsonStr = jsonObject.toString();
        String[] strArr = jsonObject.split(",");
    
        List<String> jsonObjectsValues = new ArrayList<String>();
        for(int i=0;i<strArr.length;i++){
            jsonObjectsValues.add(strArr[i].split(":")[1]);
        }
        jsonObjectsResultData.add(jsonObjectsValues);
    }
    //Your result array list
    Log.i("RESULT DATA >>", jsonObjectsResultData.toString());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多