I am trying to de-serialize a list of objects from a JSON response. The JSON array has a key, which is causing issues with using GSON to de-serialize it.
I have about 20 objects similar to this.
public class Device extends Entity {
String device_id;
String device_type;
String device_push_id;
}
For most there is an API method which returns a list of objects. The returned JSON looks like this. Because of other clients, changing the format of the JSON is not a reasonable option at this point.
{
"devices":[
{
"id":"Y3mK5Kvy",
"device_id":"did_e3be5",
"device_type":"ios"
},
{
"id":"6ZvpDPvX",
"device_id":"did_84fdd",
"device_type":"android"
}
]
}
In order to parse this type of response I'm currently using a mix of org.json
methods and Gson.
JSONArray jsonResponse = new JSONObject(response).getJSONArray("devices");
Type deviceListType = new TypeToken<List<Device>>() {}.getType();
ArrayList<Device> devices = gson.fromJson(jsonResponse.toString(), deviceListType);
I'm looking for a cleaner method of doing the deserialization as I'd like to use Retrofit. The answer in Get nested JSON object with GSON using retrofit is close to what I need, but doesn't handle List
s. I've copied the generic version of the answer here:
public class RestDeserializer<T> implements JsonDeserializer<T> {
private Class<T> mClass;
private String mKey;
public RestDeserializer(Class<T> targetClass, String key) {
mClass = targetClass;
mKey = key;
}
@Override
public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
throws JsonParseException {
JsonElement value = jsonElement.getAsJsonObject().get(mKey);
if (value != null) {
return new Gson().fromJson(value, mClass);
} else {
return new Gson().fromJson(jsonElement, mClass);
}
}
}
My goal is to have this call "just work".
@GET("/api/v1/protected/devices")
public void getDevices(Callback<List<Device>> callback);