####Spring序列化
场景
Controller
package com.baidu.test
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
public class AuditController{
@GetMapping("/detail.json")
public Object countdetail(Long id){
}
@GetMapping("/countyList.json")
public Object countList(CountryParam param){
}
@PostMapping("/addCountry.json")
public Object addCountry(@RequestBody CountryParam param){
}
}
Param
package com.baidu.test.param
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CountryParam{
private CountryEnum country;
private String name;
private Integer peopleCount;
private Long id;
}
Enum
package com.baidu.test.type;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Getter;
import org.jooq.types.UInteger;
import java.util.HashMap;
import java.util.Map;
/**
* @author wangjinliang.wjl
* @date 2019/01/14
**/
public enum CountryEnum {// 在这里定义枚举值
CHINA(1, "中国"),
USA(2, "美国"),
UK(3, "英国");
@Getter
@JsonValue
private UInteger value;
@Getter
private String name;
CountryEnum(Integer value, String name) {
this.value = UInteger.valueOf(value);
this.name = name;
}
@JsonCreator
public static CountryEnum fromValue(Integer value) {
return MAP.get(UInteger.valueOf(value));
}
public static CountryEnum fromValue(UInteger value) {
return MAP.get(value);
}
public static CountryEnum fromValue(String value) {
return MAP.get(UInteger.valueOf(value));
}
private static final Map<UInteger, CountryEnum> MAP = new HashMap<>();
static {
for (CountryEnum item : CountryEnum.class.getEnumConstants()) {
MAP.put(item.getValue(), item);
}
}
}
Deserializer
package com.baidu.test.spring.deserializer;
import com.alibaba.soc3.type.CountryEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* @author wangjinliang.wjl
* @date 2019/01/10
**/
@Component
public class SpringConverterCountryEnumInteger implements Converter<String, CountryEnum> {
@Override
public CountryEnum convert(String stat) {
if(StringUtils.isNumeric(stat)){
Integer statCode = Integer.valueOf(stat);
return CountryEnum.fromValue(statCode);
}
return CountryEnum.fromValue(stat);
}
}