I am trying to de-serialize a list of objects from a JSON response. There is a key in the JSON array that causes problems using GSON for de-serialization.
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 that returns a list of objects. The returned JSON looks like this. Due to other clients, changing the JSON format is currently not a smart option.
{ "devices":[ { "id":"Y3mK5Kvy", "device_id":"did_e3be5", "device_type":"ios" }, { "id":"6ZvpDPvX", "device_id":"did_84fdd", "device_type":"android" } ] }
To parse this type of response, I am currently using a combination of the org.json and Gson methods.
JSONArray jsonResponse = new JSONObject(response).getJSONArray("devices"); Type deviceListType = new TypeToken<List<Device>>() {}.getType(); ArrayList<Device> devices = gson.fromJson(jsonResponse.toString(), deviceListType);
I am looking for a cleaner method for doing deserialization, since I would like to use Retrofit. The answer in Get a nested JSON object using GSON using a modified version is close to what I need, but does not process List s. I copied the general 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 make this call "just work."
@GET("/api/v1/protected/devices") public void getDevices(Callback<List<Device>> callback);
java json android gson retrofit
Derek
source share