Ogulcan Ogulcan - 2 months ago 23
Android Question

How to Parse JSON Array in Android with Gson

I want to parse JSON arrays and using gson. Firstly, I can log JSON output, server is responsing to client clearly.

Here is my JSON output:

[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]


I tried this structure for parsing. A class, which depends on single
array
and
ArrayList
for all JSONArray.

public class PostEntity {

private ArrayList<Post> postList = new ArrayList<Post>();

public List<Post> getPostList() {
return postList;
}

public void setPostList(List<Post> postList) {
this.postList = (ArrayList<Post>)postList;
}
}


Post class:

public class Post {

private String id;
private String title;

/* getters & setters */
}


When I try to use gson no error, no warning and no log:

GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();

PostEntity postEnt;
JSONObject jsonObj = new JSONObject(jsonOutput);
postEnt = gson.fromJson(jsonObj.toString(), PostEntity.class);

Log.d("postLog", postEnt.getPostList().get(0).getId());


What's wrong, how can I solve?

Answer

You can parse the JSON array directly, don't need wrap your Post with PostEntity one more time, don't need new JSONObject().toString() either:

Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = (List<Post>) gson.fromJson(jsonOutput, listType);

Hop that help.