How to parse a JSON array using Gson

I want to parse JSON arrays and use gson. Firstly, I can log JSON output, the server responds clearly to the client.

Here is my JSON output:

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

I tried this structure for parsing. A class that depends on a 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; } } 

Publication Class:

  public class Post { private String id; private String title; /* getters & setters */ } 

When I try to use gson without errors, there are no warnings and no logs:

  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 is wrong, how can I decide?

+45
java json android arrays gson
Dec 03 2018-11-12T00:
source share
4 answers

You can parse the JSON array directly, no longer need to wrap your PostEntity class PostEntity and no longer need a new JSONObject (). toString ():

 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); 

Hope this helps.

+157
Dec 03 2018-11-21T00:
source share

I was looking for a way to analyze arrays of objects in a more general way; here is my contribution:

CollectionDeserializer.java :

 import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; public class CollectionDeserializer implements JsonDeserializer<Collection<?>> { @Override public Collection<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0]; return parseAsArrayList(json, realType); } /** * @param serializedData * @param type * @return */ @SuppressWarnings("unchecked") public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) { ArrayList<T> newArray = new ArrayList<T>(); Gson gson = new Gson(); JsonArray array= json.getAsJsonArray(); Iterator<JsonElement> iterator = array.iterator(); while(iterator.hasNext()){ JsonElement json2 = (JsonElement)iterator.next(); T object = (T) gson.fromJson(json2, (Class<?>)type); newArray.add(object); } return newArray; } } 

JSONParsingTest.java :

 public class JSONParsingTest { List<World> worlds; @Test public void grantThatDeserializerWorksAndParseObjectArrays(){ String worldAsString = "{\"worlds\": [" + "{\"name\":\"name1\",\"id\":1}," + "{\"name\":\"name2\",\"id\":2}," + "{\"name\":\"name3\",\"id\":3}" + "]}"; GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Collection.class, new CollectionDeserializer()); Gson gson = builder.create(); Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class); assertNotNull(decoded); assertTrue(JSONParsingTest.class.isInstance(decoded)); JSONParsingTest decodedObject = (JSONParsingTest)decoded; assertEquals(3, decodedObject.worlds.size()); assertEquals((Long)2L, decodedObject.worlds.get(1).getId()); } } 

World.java :

 public class World { private String name; private Long id; public void setName(String name) { this.name = name; } public String getName() { return name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } 
+5
Jul 29 '12 at 23:09
source share
 Type listType = new TypeToken<List<Post>>() {}.getType(); List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType); 
+2
Sep 29 '16 at 11:22
source share

Some of the answers to this post are valid, but using TypeToken, the Gson library generates Tree objects with unrealistic types for your application.

To get this, I had to read the array and convert one by one the objects inside the array. Of course, this method is not the fastest, and I do not recommend using it if your array is too large, but it worked for me.

You must include the Json library in the project. If you are developing Android, it turns on:

 /** * Convert JSON string to a list of objects * @param sJson String sJson to be converted * @param tClass Class * @return List<T> list of objects generated or null if there was an error */ public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){ try{ Gson gson = new Gson(); List<T> listObjects = new ArrayList<>(); //read each object of array with Json library JSONArray jsonArray = new JSONArray(sJson); for(int i=0; i<jsonArray.length(); i++){ //get the object JSONObject jsonObject = jsonArray.getJSONObject(i); //get string of object from Json library to convert it to real object with Gson library listObjects.add(gson.fromJson(jsonObject.toString(), tClass)); } //return list with all generated objects return listObjects; }catch(Exception e){ e.printStackTrace(); } //error: return null return null; } 
+1
Nov 28 '17 at 17:47
source share



All Articles