Jackson 实现多态反序列化

@Getter
@Setter
@ToString
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.EXISTING_PROPERTY,
        property = "msgId",
        defaultImpl = Msg.class,
        visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = MsgPing.class, name = Msg.RECEIVE_MSG_ID_PING)
})
public class Msg {
    public static final String RECEIVE_MSG_ID_PING = "ping";

    private static final ObjectMapper objectMapper = JsonMapper.builder()
            .addModules(new JavaTimeModule())
            .configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true).build();

    private String msgId;

    public static TextMessage toTextMsg(Msg msg) {
        String textMsg = toJson(msg);
        return new TextMessage(textMsg);
    }

    public static String toJson(Msg msg) {
        try {
            return objectMapper.writeValueAsString(msg);
        } catch (JsonProcessingException e) {
            log.error("Could not serialize {}", msg, e);
            return "{\"explain\":\"消息序列化失败\",\"msgId\":\"error\"}";
        }
    }

    public static Msg fromJson(String json) {
        try {
            return objectMapper.readValue(json, Msg.class);
        } catch (JsonProcessingException e) {
            log.error("Can not deserialization message", e);
            Msg msg = new Msg();
            msg.setMsgId("");
            return msg;
        }
    }
}
posted @ 2025-03-23 00:14  seliote  阅读(22)  评论(0)    收藏  举报