实现自定义的JsonDeserializer反序列化器,通过@JsonDeserialize注解,绑定在对应的类上。那么Controller在序列化和反序列化时都会走自定义的逻辑
注意: 代码中我加上了value.equals(attrType.name())
这个判断,这个就是默认的枚举类反序列化逻辑,此处为了兼容上默认的反序列逻辑。
package com.rycem.entity.analysis;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.node.TextNode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 筛选条件所属分组
**/
@JsonDeserialize(using = AttrType.CustomJsonDeserialize.class)
@AllArgsConstructor
@Getter
public enum AttrType {
EVENT_ATTR("事件属性", Arrays.asList(AttrTypeCode.DYNAMIC_ATTR.getCode(), AttrTypeCode.PRE_COL.getCode()), null),
USER_ATTR("用户属性", Arrays.asList(AttrTypeCode.DYNAMIC_ATTR.getCode(), AttrTypeCode.PRE_COL.getCode()), null),
USER_GROUP("用户分群", Arrays.asList(AttrTypeCode.DYNAMIC_ATTR.getCode(), AttrTypeCode.PRE_COL.getCode()), "xx"),
USER_TAG("用户标签", Arrays.asList(AttrTypeCode.DYNAMIC_ATTR.getCode(), AttrTypeCode.PRE_COL.getCode()), "xx"),
/* 触发环境就是固定列 */
TRIGGER_ENV("触发环境", Collections.singletonList(AttrTypeCode.FIXED_COL.getCode()), null);
private final String attrType;
private final List<Integer> typeCodes;
/* 在按xx分组时,colType不为null,直接使用colType进行groupby */
/* 在按xx分组时,colType为null,展开该类型下的具体属性进行 */
private final String colType;
public static class CustomJsonDeserialize extends JsonDeserializer<AttrType> {
@Override
public AttrType deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JacksonException {
//解析Json
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
String value = ((TextNode) treeNode).asText();
for (AttrType attrType : AttrType.values()) {
if (value.equals(attrType.attrType) || value.equals(attrType.name())) {
return attrType;
}
}
throw new RuntimeException("无法命中AttrType");
}
}
}
评论区