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

查看:26
本文介绍了将一个 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 个活动项目)的字符串列表转换为列表,该列表应将列表大小视为 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 ,试试这个链接 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 类,您可以查看 这个链接 来创建一个兼容的 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

Nullity check :有时您可能会在值不可用时看到一些异常,因此在您不确定值是否存在的情况下所以使用 optInt optBoolean 等,如果它不存在,它将简单地返回默认值,甚至尝试将值转换为 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天全站免登陆