How to parse JSON data using GSON? and put it in an ArrayList

I am trying to parse data from a MongoDB cloud server. My JSON data returned from the server is as follows:

[ { "_id": { "$oid": "4e78eb48737d445c00c8826b" }, "message": "cmon", "type": 1, "loc": { "longitude": -75.65530921666667, "latitude": 41.407904566666666 }, "title": "test" }, { "_id": { "$oid": "4e7923cb737d445c00c88289" }, "message": "yo", "type": 4, "loc": { "longitude": -75.65541383333333, "latitude": 41.407908883333334 }, "title": "wtf" }, { "_id": { "$oid": "4e79474f737d445c00c882b2" }, "message": "hxnxjx", "type": 4, "loc": { "longitude": -75.65555572509766, "latitude": 41.41263961791992 }, "title": "test cell" } 

]

The problem I encountered is the returned data structure, which does not include the name of the array of JSON objects. Each returned object is a "message". But how to parse it using GSON if there is no name for the array of JSON objects. I would like to put these "posts" in an ArrayList like Post.

+4
source share
2 answers

The code for the snippet you are looking for:

 String jsonResponse = "bla bla bla"; Type listType = new TypeToken<List<Post>>(){}.getType(); List<Post> posts = (List<Post>) gson.fromJson(jsonResponse, listType); 
+13
source

Use the constructor for JSONArray to parse the string:

 //optionally use the com.google.gson.Gson package Gson gson = new Gson(); ArrayList<Post> yourList = new ArrayList<Post>(); String jsonString = "your string"; JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++){ Post post = new Post(); //manually parse for all 5 fields, here an example for message post.setMessage(jsonArray.get(i).getString("message")); //OR using gson...something like this should work //post = gson.fromJson(jsonArray.get(i),Post.class); yourList.Add(post); } 

Given that there are only 5 fields, using Gson may be more overhead than you need.

+1
source

All Articles