问题描述
我有树的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));
}
不过,这种方式是错误的。执行方法列表后填写相同的数据。
But this way is wrong. After execution of the method List filled out same data.
我如何分析它吗?
UPD:更新JSON。
UPD: update JSON.
推荐答案
忽略你展示的JSON是无效的(我要去假设这是一个复制/粘贴问题或拼写错误),问题是,你声明你的类别
名录无论对象是其成员。
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()
和数据保留在列表中。从你的循环每次后续调用是看到放在它的任何previous电话。
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.
有一个简单的解决方案,这是你的code被写入是简单地添加清除列表中的第二个版本:
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);
}
然后调用,从你的循环。
Then call that from your loop.
这篇关于Android的解析JSON树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!