Skip to content Skip to sidebar Skip to footer

How To Skip Null Entries With Gson

When deserializing JSON with Gson, is there a way to skip null entries in a JSON array? [ { text: 'adsfsd...', title: 'asdfsd...' }, null, {

Solution 1:

You can exclude null values by writing your own custom gson JsonDeserializer

Assuming that you have your model class

classGetData {
    private String title;
    private String text;
}

classCustomDeserializerimplementsJsonDeserializer<List<GetData>> {

    @Overridepublic List<GetData> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)throws JsonParseException {

       JsonArrayjsonArray=    jsonElement.getAsJsonArray();

       List<GetData>  list=newArrayList<>(30);
       Gsongson=newGson();

       for (JsonElement element : jsonArray) {
           // skipping the null here, if not null then parse json element and add in collectionif(!(element instanceof JsonNull))
           {
               list.add(gson.fromJson(element,  GetData.class));
           }
        }

        return list;
    }

Finally you can parse it

Gson gson = newGsonBuilder().registerTypeHierarchyAdapter(Collection.class, newCustomDeserializer()).create();
gson.fromJson(builder.toString(), Collection.class);

Solution 2:

Null values are excluded by default as long as you don't set serializeNulls() to your GsonBuilder. Once I found this. and worked for me:

classCollectionAdapterimplementsJsonSerializer<Collection<?>> {
  @Override
  public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) {
    if (src == null || src.isEmpty()) // exclusion is made herereturnnull;

    JsonArray array = new JsonArray();

    for (Object child : src) {
      JsonElement element = context.serialize(child);
      array.add(element);
    }

    returnarray;
  }
}

Then register this by this code:

Gson gson = newGsonBuilder().registerTypeHierarchyAdapter(Collection.class, newCollectionAdapter()).create();

Hope this helps.. :)

Post a Comment for "How To Skip Null Entries With Gson"