优雅地在Java应用中实现全局枚举处理的方法

2019-09-13 11:24:06王冬梅

@Configuration
@Slf4j
public class JacksonConfiguration {

 /**
  * Jackson的转换器
  * @return
  */
 @Bean
 @Primary
 @SuppressWarnings({"rawtypes", "unchecked"})
 public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
  final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
  ObjectMapper objectMapper = converter.getObjectMapper();
  // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
  // 反序列化时候,遇到多余的字段不失败,忽略
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  // 允许出现特殊字符和转义符
  objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
  // 允许出现单引号
  objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
  SimpleModule customerModule = new SimpleModule();
  customerModule.addDeserializer(String.class, new StringTrimDeserializer(String.class));
  customerModule.addDeserializer(Enumerable.class, new EnumDeserializer(Enumerable.class));
  customerModule.addSerializer(Enumerable.class, new EnumSerializer(Enumerable.class));
  objectMapper.registerModule(customerModule);
  converter.setSupportedMediaTypes(ImmutableList.of(MediaType.TEXT_HTML, MediaType.APPLICATION_JSON));
  return converter;
 }

}
public class EnumDeserializer<E extends Enumerable> extends StdDeserializer<E> {

 private Class<E> enumType;

 public EnumDeserializer(@Nonnull Class<E> enumType) {
  super(enumType);
  this.enumType = enumType;
 }

 @Override
 public E deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
  return EnumUtil.of(this.enumType, jsonParser.getIntValue());
 }

}

【出参】当我们查询出结果,要展示给前台的时候,我们会对结果集增加@ResponseBody注解,这时候会调用Jackson的序列化方法,所以我们增加了枚举类的序列配置。如果我们只简单的将枚举转换成 int 给前台,那么前台需要维护这个枚举类的 int 和对应展示信息的关系。所以这块我们将值和展示信息一同返给前台,减轻前台的工作压力。

// 注册枚举类序列化处理类
customerModule.addSerializer(Enumerable.class, new EnumSerializer(Enumerable.class));

public class EnumSerializer extends StdSerializer<Enumerable> {

 public EnumSerializer(@Nonnull Class<Enumerable> type) {
  super(type);
 }

 @Override
 public void serialize(Enumerable enumerable, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
  jsonGenerator.writeStartObject();
  jsonGenerator.writeNumberField("value", enumerable.getValue());
  jsonGenerator.writeStringField("text", enumerable.getText());
  jsonGenerator.writeEndObject();
 }
}