将一个JSONAray项目转换为多个项目 [英] Convert one JSONAray item into multiple Items

查看:68
本文介绍了将一个JSONAray项目转换为多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串,它以列表的形式从数据库返回,我的假设是,列表包含3个项目. 但大小仅显示"1".因此它将所有活动项作为一个元素返回.

I have the following String which is returning from the Database in the form of List, My assumption is that, the list contains 3 items. but it is showing only "1" as the size. So it is returning all the activity items as one element.

注意:当我尝试获取列表的第一个索引(list.get(0))时,它仅返回一个活动",而不是全部三个(作为单个项目).我不知道这是什么 发生在列表中.

Note: When I try to get the first index of the list (list.get(0)), it returns only one "activity" not all the three(as a single item).I don't know what is happening inside the list.

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

My Question: How to convert the below list of strings which contains 1 item(with 3 activity items) into List which should consider list size as 3(3 activity).

[ { "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" }}]

以上信息来自数据库:

Iterable<DBObject> results =null;
List<String> retList = new ArrayList<>();
        try {
            results= collection.aggregate(pipeline).results();
        } catch (Exception e) {
        }
        if(results!=null){
            Iterator<DBObject> 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数组

1.) create json array by passing your string to constructor

2.)遍历数组并使用索引i

2.) traverse array and retrieve your jsonObject using index i

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

3.) fetch the activity jsonobject and then simply use your index to fetch the values for jsonActivityItem object.

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

4.) create a POJO class to store your object in a collection like List etc but make sure to mark them private and use getter and setters for best practice

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

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

Note : To convert your string to json compatible you can use JsonParser , try this link JsonParser snippet

    JSONArray array;
    List<User> 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<array.length();i++) {
            System.out.println();
            jsonActivity=array.getJSONObject(i);
            jsonActivityItem=jsonActivity.getJSONObject("activity");                


            // 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类,可以查看 Gson代码

I would recommend an easy and short way i.e using gson to convert it into list but you will required to use POJO class you can take a look at this link to create a compatible POJO class and later just use Gson code

空值检查:有时,当值不可用时,您可能会看到一些例外情况,因此在不确定值是否存在的情况下,您可能会看到一些例外情况 因此,请使用optInt optBoolean等,如果不存在默认值,它将简单地返回默认值,如果它是string,甚至尝试将其转换为int

Nullity check : Sometime you may see some exceptions when the values are not available so in those cases when you are not sure about the presence of value so use optInt optBoolean etc which will simply return the default value if it is not present and even try to convert value to int if it is string like

来自

获取与键关联的可选int值,如果为默认值,则为默认值 没有这样的键,或者值不是数字.如果值为 字符串,将尝试将其评估为数字.

Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

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

例如

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

这篇关于将一个JSONAray项目转换为多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆