Skip to content

Instantly share code, notes, and snippets.

@rogerhu
Created February 12, 2016 05:58
Show Gist options
  • Save rogerhu/d017c8e7ecda38c775b4 to your computer and use it in GitHub Desktop.
Save rogerhu/d017c8e7ecda38c775b4 to your computer and use it in GitHub Desktop.
MultimEdia deserializer
package codepath.com.nytimesfun;
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;
import android.text.TextUtils;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* Created by rhu on 12/17/15.
*/
public class MultimediaDeserializer implements JsonDeserializer<List<Multimedia>> {
@Override
public List<Multimedia> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
ArrayList<Multimedia> multimedias = new ArrayList<>();
String str = null;
try {
str = json.getAsString();
} catch (IllegalStateException e) {
}
if (str != null && TextUtils.isEmpty(str)) {
return multimedias;
} else {
JsonArray jsonArray = json.getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
multimedias.add((Multimedia) context.deserialize(jsonArray.get(i), Multimedia.class));
}
}
return multimedias;
}
}
@AmitGoenka
Copy link

This class is rendering an UnsupportedOperationException when the size of the array is 1.

@AmitGoenka
Copy link

The solution may look like this:

@OverRide
public List deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List multimediaList = new ArrayList<>();
String jsonString = null;

    try {
        jsonString = json.getAsString();
    } catch (IllegalStateException | UnsupportedOperationException e) {
       // Do Nothing
    }

    if (jsonString == null || !TextUtils.isEmpty(jsonString)) {
        JsonArray jsonArray = json.getAsJsonArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            multimediaList.add(context.deserialize(jsonArray.get(i), Multimedia.class));
        }
    }

    return multimediaList;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment