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 <T> List<T> fromJsonList(String json, Class<T> pojoClass) throws IOException {
if (json == null) {
return null;
}
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, pojoClass);
return MAPPER.readValue(json, javaType);
}
public static <T> List<T> fromJsonList(byte[] json, Class<T> pojoClass) throws IOException {
if (json == null) {
return null;
}
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, pojoClass);
return MAPPER.readValue(json, javaType);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。