我有一个json字符串,我想映射到我的java对象。我目前正在使用gson这样做。但是,问题是,我已经设置了POJO的一部分,以包含一个抽象类。如何正确映射与此抽象类对应的json?
澄清:
下面是我目前正在接收的json字符串的一个示例:
{
"Items" : [
{
"id" : "ID1",
"seller_id": 17,
"item_plan": {
"action" : "Sell"
}
},
{
"id" : "ID2",
"seller_id": 27,
"item_plan": {
"action": "Remove",
}
}
]
}我的请求对象的设置如下:
public class RequestObject {
@SerializedName("Items")
@Expose
private List<Item> items = null;
public class Item {
@SerializedName("id")
@Expose
private String id;
@SerializedName("seller_id")
@Expose
private Integer sellerID;
@SerializedName("item_Plan")
@Expose
private ItemPlan item_plan;
public abstract class ItemPlan {
@SerializedName("action")
@Expose
private String action;
public abstract void executePlan()如您所见,我的request对象有一个表示item_plan的抽象类。这里的想法是,item_plan操作将有自己的执行方式,因此有一个名为ItemPlan的父类,其中每个子类将表示可能的操作计划和自己的executionPlan,即。(SellPlan是ItemPlan的子类,SellPlan有自己的函数executionPlan()实现)。
如何将示例json字符串映射到以下Java类?
我尝试了以下几点:
RuntimeTypeAdapterFactory<ItemPlan> itemPlanRuntimeTypeAdapterFactory =
RuntimeTypeAdapterFactory
.of(ItemPlan.class, "action")
.registerSubtype(SellPlan.class, "Sell")
.registerSubtype(RemovePlan.class, "Remove");
Gson gson = new
GsonBuilder().registerTypeAdapterFactory(itemPlanRuntimeTypeAdapterFactory).create();
RequestObject request = gson.fromJson(jsonString, RequestObject.class);然而,这是行不通的。它能够映射我所需要的一切,但是它无法创建正确的创建抽象类对象,即。虽然它将创建相应的子对象(SellPlan表示Sell,RemovePlan用于删除),但它将使这些类的操作字符串为空。有一个解决办法,我可以简单地在这些类的构造函数中手动设置操作字符串,但我不愿意。有办法解决这个问题吗?
谢谢。
发布于 2022-07-02 18:20:36
您可能必须将RuntimeTypeAdapterFactory.of重载与附加的maintainType参数一起使用,然后将true作为值传递。否则,正如您已经注意到的,Gson在序列化期间移除类型字段值,因此该字段保留其默认值null。
https://stackoverflow.com/questions/72836444
复制相似问题