java - 反序列化多态 JSON 字符串

标签 java json serialization jackson deserialization

我有几个 POJO,它们都具有相同的抽象基类。我想在不进行类型检查或强制转换的情况下进行序列化和反序列化。

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.WRAPPER_OBJECT,
    property = "type"
)
@JsonSubTypes({
        @JsonSubTypes.Type(value = UserEvent.class, name = "user"),
        @JsonSubTypes.Type(value = SystemEvent.class, name = "system")
})
public abstract class Event {
    private Long id;
    private Date date;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

@JsonTypeName("user")
public class UserEvent extends Event {

    private String userId;
    private String userName;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

@JsonTypeName("system")
public class SystemEvent extends Event {

    private String source;

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }
}

当我将 UserEvent 序列化为 JSON 时,我得到以下输出,类型名称为包装对象。

{
  "user" : {
    "id" : 42,
    "date" : 1568214606656,
    "userId" : "123123",
    "userName" : "Bob"
  }
}

到目前为止一切顺利。如果我尝试反序列化同一个 JSON 对象,它会失败。

@Test
void deserializeUserEvent() throws Exception {
    String json =
            "\"user\" : {\n" +
            "    \"id\" : 42,\n" +
            "    \"date\" : 1568211488351,\n" +
            "    \"userId\" : \"123123\",\n" +
            "    \"userName\" : \"Bob\"\n" +
            "  }";

    ObjectMapper mapper = new ObjectMapper();
    Event event = mapper
            .readerFor(Event.class)
            .readValue(json); // ERROR

    assertSame(UserEvent.class, event.getClass());
}

是否可以通过只声明抽象类型来反序列化具体类型?

最佳答案

是的,你可以使用它。我在这里使用对象映射器将您的对象写为字符串。

    UserEvent ue = new UserEvent();
    ue.setUserName("Some Username");
    ue.setUserId("userID");
    ue.setDate(new Date());
    ue.setId(123123L);
    ObjectMapper objectMapper = new ObjectMapper();
    String userEventString = objectMapper.writeValueAsString(ue);

{"user":{"id":123123,"date":1568217548148,"userId":"userID","userName":"asdlasd"}}

读作:

Event event = objectMapper.readValue(userEventString, Event.class);

而且 ObjectMapper 还为您提供了使用的可能性:

ObjectMapper mapperWithMixin = new ObjectMapper()
        .addMixIn(Event.class, UserEvent.class);

其中 Event.class 是您的目标类,而 UserEvent.class 是您提供的 json 对象。

关于java - 反序列化多态 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57892310/

相关文章:

java - mock 幂等消费者

php - 使用 mySQL 和 php 创建正确的 JSON

javascript - 根据对象的数量将每个 JSON 对象及其项目放入 <li> 中

javascript - 使用jquery获取与json对象中提供的值匹配的对象?

java - 本地 Maven 存储库位置

java - 我应该使用相同的 HttpUrlconnection 还是每次都定义一个新的连接?

python - 将 networkx DiGraph 打印为嵌套的 JSON 格式

c++ - 如何以惯用的方式实现 C++ 序列化程序?

C# 序列化对象集合

java - Google Analytics 版本 4 API java 最大结果