Java GSON对象包装列表的反序列化
我正在尝试从JSON响应中反序列化对象列表。JSON数组有一个键,这导致使用GSON对其进行反序列化时出现问题 我有大约20个类似的物体Java GSON对象包装列表的反序列化,java,android,json,gson,retrofit,Java,Android,Json,Gson,Retrofit,我正在尝试从JSON响应中反序列化对象列表。JSON数组有一个键,这导致使用GSON对其进行反序列化时出现问题 我有大约20个类似的物体 public class Device extends Entity { String device_id; String device_type; String device_push_id; } 对于大多数情况,有一个API方法返回对象列表。返回的JSON如下所示。由于其他客户端的原因,此时更改JSON的格式不是一个合理的选择 { "d
public class Device extends Entity {
String device_id;
String device_type;
String device_push_id;
}
对于大多数情况,有一个API方法返回对象列表。返回的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);
我的目标是让这个电话“公正工作”
@GET(“/api/v1/protected/devices”)
公用设备(回调);
使用下面的类
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;
}
}
或
将改装方法更新为
@GET("/api/v1/protected/devices")
public void getDevices(Callback<Devices> callback);
devices.getDevices() //call inside callback method will give you the list
@GET(“/api/v1/protected/devices”)
公用设备(回调);
devices.getDevices()//调用内部回调方法将为您提供列表
此外,您不需要自定义反序列化程序,它不是一个简单的
列表吗?如果字段名与Json名称不同,只需使用@SerializedName
注释即可。“改装”将为您进行解析。您如何创建和注册反序列化程序?我目前没有使用反序列化程序,因为它实际上无法解决问题。@Marcacierno,我没有包含设备列表的类。我试图避免创建不需要的(希望是不必要的!)包装类。@Derek,你是如何解决这个问题的。你能把你的答案贴出来吗?我考虑过这一点,事实上,如果没有通用选项出现,我会这么做。但是,因为我有20多个这样的对象,我希望避免仅仅为了包装列表而增加20个类;我自己也没试过,如果有用就告诉我。。如果此操作无效,则不必创建额外的对象。问题是,Gson如何知道名为“devices”的json元素是正确的,可以展开以找到它的列表或设备[]。列表应该可以工作,您尝试过了吗?改装在内部使用gson并为您处理映射。如果不进行改造,您将不得不编写自己的反序列化程序,我已经尝试过这个列表。问题是gson无法自行直觉地了解如何打开{“设备”:[{…设备…},{…设备…}]}。上面的泛型反序列化器是一种解包单个对象的紧凑方式,但是java中没有用于参数化类型(如List
)的类文本。您给了我使用Device[]
的想法,它确实有一个类文本。我现在就想办法解决这个问题。谢谢
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;
}
}
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