【发布时间】:2014-03-18 01:17:57
【问题描述】:
我有树 JSON 结构的数据。 类似的东西
{
"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 解析
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方法执行后填写相同的数据。
如何正确解析?
UPD:更新 JSON。
【问题讨论】:
-
您的回复无效,请查看jsonlint.com
-
@YuriyAizenberg:我面临同样的问题..我没有得到下面写的解决方案..你能告诉我你做了什么改变让它工作吗?
标签: android json recursion tree