Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Parse JSON Array 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?

like image 968
Ogulcan Orhan Avatar asked Dec 03 '11 21:12

Ogulcan Orhan


1 Answers

You can parse the JSONArray directly, don't need to wrap your Post class with PostEntity one more time and 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 = gson.fromJson(jsonOutput, listType); 

Hope that helps.

like image 120
yorkw Avatar answered Sep 20 '22 09:09

yorkw