GSON deserialization of a wrapped list of objects

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); 
+7
java json android gson retrofit
source share
1 answer

Use the class below

 public class Devices { @Expose private List<Device> devices = new ArrayList<Device>(); /** * * @return * The devices */ public List<Device> getDevices() { return devices; } /** * * @param devices * The devices */ public void setDevices(List<Device> devices) { this.devices = devices; } } 

Device class

 public class Device extends Entity { @Expose String id; @Expose String device_id; @Expose String device_type; } 

or

 public class Device extends Entity { @Expose @SerializedName("id") String deviceId; @Expose @SerializedName("device_id") String devicePushId; @Expose @SerializedName("device_type") String deviceType; } 

update refinement method

 @GET("/api/v1/protected/devices") public void getDevices(Callback<Devices> callback); devices.getDevices() //call inside callback method will give you the list 

In addition, you do not need a custom deserializer

+1
source share

All Articles