包装对象列表的 GSON 反序列化

GSON deserialization of a wrapped list of objects

我正在尝试从 JSON 响应中反序列化对象列表。 JSON 数组有一个键,这会导致使用 GSON 对其进行反序列化时出现问题。

我有大约 20 个类似的对象。

public class Device extends Entity {
  String device_id;
  String device_type;
  String device_push_id;
}

对于大多数人来说,有一个 API 方法,其中 returns 对象列表。返回的 JSON 看起来像这样。由于其他客户端,更改 JSON 的格式目前不是一个合理的选择。

{
   "devices":[
      {
         "id":"Y3mK5Kvy",
         "device_id":"did_e3be5",
         "device_type":"ios"
      },
      {
         "id":"6ZvpDPvX",
         "device_id":"did_84fdd",
         "device_type":"android"
      }
   ]
}

为了解析这种类型的响应,我目前正在混合使用 org.json 方法和 Gson。

JSONArray jsonResponse = new JSONObject(response).getJSONArray("devices");

Type deviceListType = new TypeToken<List<Device>>() {}.getType();
ArrayList<Device> devices = gson.fromJson(jsonResponse.toString(), deviceListType);

我正在寻找一种更简洁的反序列化方法,因为我想使用 Retrofit。 Get nested JSON object with GSON using retrofit 中的答案接近我需要的,但不处理 List。我在这里复制了通用版本的答案:

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);
    }
  }
}

我的目标是打这个电话 "just work"。

@GET("/api/v1/protected/devices")
public void getDevices(Callback<List<Device>> callback);

使用下面的class

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;
}

}

设备class

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

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

将改造方法更新为

@GET("/api/v1/protected/devices")
public void getDevices(Callback<Devices> callback);

devices.getDevices() //call inside callback method will give you the list

此外,您不需要自定义解串器