Jackson的使用

Jackson的使用

枚举的序列化和反序列化

使用@JsonValue和@JsonCreator

public enum LivePollingMethod {

    /**
     * 直播室弹幕
     */
    WEB_CAST_CHAT("WebcastChatMessage"),

    /**
     * 谁进入直播间
     */
    WEB_CAST_MEMBER("WebcastMemberMessage"),


    /**
     * 直播间用户排行
     */
    WEB_CAST_ROOM_USER_SEQ("WebcastRoomUserSeqMessage"),

    /**
     * 送礼物消息
     */
    WEB_CAST_GIFT("WebcastGiftMessage"),

    /**
     * 正在购买消息
     */
    WEB_CAST_LIVE_ECOM("WebcastLiveEcomMessage");

    private String method;

    LivePollingMethod(String method) {

        this.method = method;
    }

    @JsonValue
    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    @JsonCreator
    public static LivePollingMethod getItem(String message) {
        for (LivePollingMethod item : values()) {
            if (item.getMethod().equals(message)) {
                return item;
            }
        }
        return null;
    }
}

使用JsonType

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "method"
)
@JsonSubTypes({
        @JsonSubTypes.Type(value = BuyingLivePollingImpl.class, name = "WebcastLiveEcomMessage"),
        @JsonSubTypes.Type(value = UserCountLivePollingImpl.class, name = "WebcastMemberMessage")
})
public class BaseDyLivePolling implements Serializable {

    private String authorId;

    private String msgId;

    private String roomId;

    private long createTime;
}

反序列化List

public class ScalaJsonUtil {


    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        
    // 使用Scala的时候
    MAPPER.registerModule(new DefaultScalaModule());
    // 忽略不认识的字段
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
 
public static  List fromJsonList(String json, Class pojoClass) throws IOException {
        if (json == null) {
            return null;
        }
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, pojoClass);

        return MAPPER.readValue(json, javaType);
    }

public static  List fromJsonList(byte[] json, Class pojoClass) throws IOException {
        if (json == null) {
            return null;
        }
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, pojoClass);

        return MAPPER.readValue(json, javaType);
    }
}

你可能感兴趣的:(jackson,java)