我有几个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/

10-17 01:38