Android Parse Json Tree
I have tree JSON-structured data. Something like { 'result': [ { 'id': 1, 'name': 'test1' }, { 'id': 2, 'name': 'test12', 'child
Solution 1:
Here is Full Demo How to Parse json data as you want.
StringJSON = "your json string";
ArrayList<DataEntity> finalResult = newArrayList<>();
try {
JSONObject main = newJSONObject(JSON);
JSONArray result = main.getJSONArray("result");
for(int i=0;i<result.length();i++){
DataEntity dataEntity = parseObject(result.getJSONObject(i));
finalResult.add(dataEntity);
}
Log.d("DONE","Done Success");
} catch (JSONException e) {
e.printStackTrace();
}
Create One recursive function to parse object.
public DataEntity parseObject(JSONObject dataEntityObject)throws JSONException {
DataEntitydataEntity=newDataEntity();
dataEntity.id = dataEntityObject.getString("id");
dataEntity.name = dataEntityObject.getString("name");
if(dataEntityObject.has("children")){
JSONArrayarray= dataEntityObject.getJSONArray("children");
for(int i=0;i<array.length();i++){
JSONObjectjsonObject= array.getJSONObject(i);
DataEntitytemp= parseObject(jsonObject);
dataEntity.children.add(temp);
}
}
return dataEntity;
}
Model Class
publicclassDataEntityimplementsSerializable {
publicStringid="";
publicStringname="";
ArrayList<DataEntity> children = newArrayList<>();}
In FinalResult Arraylist you will get all your parse data.
Solution 2:
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.
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:
privateList<DataEntity> beginRecursivellyParse(DataEntity entity,
JSONObjectobject) throws JSONException {
categories.clear();
returnrecursivellyParse(entity, object);
}
Then call that from your loop.
Post a Comment for "Android Parse Json Tree"