pringboot 针对jackson是自动化配置的,如果需要修改,有两种方式:

方式一:通过application.yml

配置属性说明:

spring.jackson.date-format指定日期格式,比如yyyy-MM-dd HH:mm:ss,或者具体的格式化类的全限定名
spring.jackson.deserialization是否开启Jackson的反序列化
spring.jackson.generator是否开启json的generators.
spring.jackson.joda-date-time-format指定Joda date/time的格式,比如yyyy-MM-ddHH:mm:ss). 如果没有配置的话,dateformat会作为backup
spring.jackson.locale指定json使用的Locale.
spring.jackson.mapper是否开启Jackson通用的特性.
spring.jackson.parser是否开启jackson的parser特性.
spring.jackson.property-naming-strategy指定PropertyNamingStrategy(CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)或者指定PropertyNamingStrategy子类的全限定类名.
spring.jackson.serialization是否开启jackson的序列化.
spring.jackson.serialization-inclusion指定序列化时属性的inclusion方式,具体查看JsonInclude.Include枚举.
spring.jackson.time-zone指定日期格式化时区,比如America/Los_Angeles或者GMT+10.

常用配置:

  1. spring:
  2. jackson:
  3. #日期格式化
  4. date-format: yyyy-MM-dd HH:mm:ss
  5. serialization:
  6. #格式化输出
  7. indent_output: true
  8. #忽略无法转换的对象
  9. fail_on_empty_beans: false
  10. #设置空如何序列化
  11. defaultPropertyInclusion: NON_EMPTY
  12. deserialization:
  13. #允许对象忽略json中不存在的属性
  14. fail_on_unknown_properties: false
  15. parser:
  16. #允许出现特殊字符和转义符
  17. allow_unquoted_control_chars: true
  18. #允许出现单引号
  19. allow_single_quotes: true

方式二:使用重新注入ObjectMapper


在配置bean中使用下面的配置

  1. @Bean
  2. @Primary
  3. @ConditionalOnMissingBean(ObjectMapper.class)
  4. public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
  5. {
  6. ObjectMapper objectMapper = builder.createXmlMapper(false).build();
  7. // 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
  8. // Include.Include.ALWAYS 默认
  9. // Include.NON_DEFAULT 属性为默认值不序列化
  10. // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
  11. // Include.NON_NULL 属性为NULL 不序列化
  12. objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
  13. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  14. // 允许出现特殊字符和转义符
  15. objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
  16. // 允许出现单引号
  17. objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
  18. // 字段保留,将null值转为""
  19. objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
  20. {
  21. @Override
  22. public void serialize(Object o, JsonGenerator jsonGenerator,
  23. SerializerProvider serializerProvider)
  24. throws IOException
  25. {
  26. jsonGenerator.writeString("");
  27. }
  28. });
  29. return objectMapper;
  30. }