枚举类enum在json序列化时返回枚举值
方法一:只需在get方法上加上@JsonValue注解即可
public enum PropertyOperation {
EQ("="),
GT(">"),
GTE(">="),
LT("<"),
LTE("<=");
private String opStr;
PropertyOperation(String opStr) {
this.opStr = opStr;
}
@JsonValue
public String getOpStr() {
return opStr;
}
}
方法二:重写serialize方法,针对PropertyOperation枚举类单独处理
public static String transformDslJsonProcess(DSL dsl){
String result = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
@Override
public void serialize(Enum anEnum, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if(anEnum instanceof PropertyOperation){
PropertyOperation propertyOperation = (PropertyOperation) anEnum;
jsonGenerator.writeString(propertyOperation.getOpStr());
}
}
});
objectMapper.registerModule(simpleModule);
result = objectMapper.writeValueAsString(dsl);
} catch (IOException e) {
log.error("json process error", e);
}
return result;
}
json序列化时忽略值为空的属性
方法一:增加spring配置文件,全局null为空不序列化
spring.jackson.default-property-inclusion=non_empty
方法二:针对某个属性,增加注解,这个属性为空序列化就不会输出这个属性
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private CombinationFormatType combinationFormatType;
json序列化时修改属性名字即Key的名称
加上@JsonProperty注解,那么在序列化时key的值就是注解括号中的值
@JsonProperty("combination_format")
private CombinationFormatType combinationFormatType;