Android解析json树 [英] Android parse json tree

查看:22
本文介绍了Android解析json树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有树 JSON 结构的数据.类似的东西

I have tree JSON-structured data. Something like

{
"result": [
    {
        "id": 1,
        "name": "test1"
    },
    {
        "id": 2,
        "name": "test12",
        "children": [
            {
                "id": 3,
                "name": "test123",
                "children": [
                    {
                        "id": 4,
                        "name": "test123"
                    }
                ]
            }
        ]
    }
]

}

型号:

class DataEntity {
    int id;
    String name;
    List<DataEntity> childDataEntity;
}

通过 org.json 解析

Parsing via org.json

    List<DataEntity> categories = new ArrayList<DataEntity>();

private List<DataEntity> recursivellyParse(DataEntity entity, JSONObject object) throws JSONException {
    entity.setId(object.getInt("id"));
    entity.setName(object.getString("name"));
    if (object.has("children")) {
        JSONArray children = object.getJSONArray("children");
        for (int i = 0; i < children.length(); i++) {
            entity.setChildDataEntity(recursivellyParse(new DataEntity(), children.getJSONObject(i)));
            categories.add(entity);
        }
    }
    return categories;
}

打电话

  JSONObject jsonObject = new JSONObject(JSON);
        JSONArray jsonArray = jsonObject.getJSONArray("result");
        for (int i = 0; i < jsonArray.length(); i++) {
            recursivellyParse(new DataEntity(), jsonArray.getJSONObject(i));
        }

但是这种方式是错误的.执行List方法后填写相同的数据.

But this way is wrong. After execution of the method List filled out same data.

我该如何正确解析?

UPD:更新 JSON.

UPD: update JSON.

推荐答案

忽略您显示的 JSON 无效(我将假设这是复制/粘贴问题或拼写错误),问题在于您已声明您的 categories 列表作为任何对象的成员.

Ignoring that the JSON you show is invalid (i'm going to assume that's a copy/paste problem or typo), the issue is that you've declared your categories List as a member of whatever object that is.

每次调用 recursivellyParse() 时都会不断添加它,并且该数据保留在列表中.循环中的每个后续调用都会查看之前放入的调用.

It's continually getting added to on every call to recursivellyParse() and that data remains in the list. Each subsequent call from your loop is seeing whatever previous calls put in it.

在编写代码时对此的一个简单解决方案是简单地添加清除列表的第二个版本:

A simple solution to this as your code is written would be to simply add a second version that clears the list:

private List<DataEntity> beginRecursivellyParse(DataEntity entity, 
                                      JSONObject object) throws JSONException {

    categories.clear();
    return recursivellyParse(entity, object);
}

然后从循环中调用它.

这篇关于Android解析json树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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