将一个JSONAray项转换为多个项

我有以下字符串,它以List的forms从数据库返回,我的假设是,该列表包含3个项目。 但它只显示“1”作为大小。 所以它将所有活动项目作为一个元素返回。

注意:当我尝试获取列表的第一个索引(list.get(0))时,它只返回一个“活动”而不是全部三个(作为单个项目)。我不知道内部发生了什么名单。

我的问题:如何将包含1个项目(包含3个活动项目)的下面的字符串列表转换为List,将列表大小视为3(3个活动)。

[ { "activity" : { "id" : "a_3" , "kind" : "Infomation" , "userId" : 100 , "accountId" : 0 , "timestamp" : 1476369009366 , "result" : "normal" }} , { "activity" : { "id" : "a_18" , "kind" : "Infomation" , "userId" : 100 , "accountId" : 0 ,"timestamp" : 1476419696003 , "result" : "normal" }} , { "activity" : { "id" : "a_4" , "kind" : "Infomation" , "userId" : 100, "accountId" : 0 , ""timestamp" : 1476435910335 , "result" : "normal" }}] 

以上信息来自DB:

 Iterable results =null; List retList = new ArrayList(); try { results= collection.aggregate(pipeline).results(); } catch (Exception e) { } if(results!=null){ Iterator iterator = results.iterator(); while (iterator.hasNext()) { String input = iterator.next().get("actLogList").toString(); retList.add(input.substring(input.indexOf("[") + 1, input.lastIndexOf("]"))); } } return retList; 

1.)通过将您的字符串传递给构造函数来创建json数组

2.)遍历数组并使用索引i检索您的jsonObject

3.)获取activity jsonobject然后只需使用索引来获取jsonActivityItem对象的值。

4.)创建一个POJO类,将您的对象存储在List等集合中,但要确保将它们标记为private并使用getter和setter进行最佳实践

 class User{ String id,kind,result; int userId,accountId; long timestamp; //.. getter & setters } 

注意:要将您的字符串转换为json兼容,您可以使用JsonParser ,尝试此链接JsonParser片段

  JSONArray array; List listUser=new ArrayList<>(); // to store objects as details try { array=new JSONArray(st); // st is your string ( make sure to use jsonparser ) JSONObject jsonActivity; JSONObject jsonActivityItem; User user; for (int i=0;i 

  // To store data for later use user = new User(); user.setId(jsonActivityItem.getString("id")); user.settimestamp(jsonActivityItem.getLong("timestamp")); //..set other values using setters listUser.add(user); 

  // to display items String id = jsonActivityItem.optString("id"); String kind = jsonActivityItem.optString("kind"); String userId = jsonActivityItem.optString("userId"); String accountId = jsonActivityItem.optString("accountId"); String timestamp = jsonActivityItem.optString("timestamp"); String result = jsonActivityItem.optString("result"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

我建议一个简单的方法,即使用gson将其转换为列表,但是你需要使用POJO类,你可以看看这个链接来创建兼容的POJO类,然后只需使用Gson代码

无效检查 :有时你可能会在值不可用时看到一些exception,所以在你不确定是否存在值的情况下所以使用optInt optBoolean等,如果它不存在,它将简单地返回默认值,甚至尝试如果它是string则将值转换为int

来自docs

获取与键关联的可选int值,如果没有此键或者值不是数字,则获取默认值。 如果值是字符串,则会尝试将其作为数字进行评估。

 int block_id = jObj.getInt("key",defaultvalue); 

例如

 int block_id = jObj.getInt("userId",0); 

您必须使用GSON库来解析此JSON数组。 您需要执行类似于以下代码的操作。

  JSONArray jsonArray = new JSONArray(jsonArrayString); List list = new ArrayList(); for (int i=0; i