@JsonProperty 失效问题的排查

 

@JsonProperty 是Jackson提供的一个用于注解属性、类、方法等的json注解。使用它可以改变Json序列化时属性的名称,一般默认使用属性名,比如如下的代码示例,如果没有使用@JsonProperty注解那么id转化为json为{“id”:11}.使用了则就是{“Id”:11}.

 
  1. @JsonInclude(Include.NON_NULL)

  2. public class User implements Serializable {

  3.  
  4. @JsonProperty("Id")

  5. private Integer id;

  6. @JsonProperty("Name")

  7. private String name;

  8. @JsonProperty("pwd")

  9. private Integer passWord;

  10. }

  • 在一次使用springboot项目时发现@JsonProperty不生效。那么是因为啥呢?
  • 因为在项目里还引用了fastJson,在debug时发现接口最后响应时是使用FastJson做json序列化。
  • 解决方法:使用@EnableWebMvc注解,加在启动类上。或者直接在项目里不引用fastJson.
     
    1. @EnableWebMvc

    2. public class SpringBootMain extends SpringBootServletInitializer implements WebApplicationInitializer {

    3.  
    4. @Override

    5. protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

    6. return application.sources(SpringBootMain.class);

    7. }

    8. }

  • springboot 是如何选择使用json序列化工具的呢?即如何调用jackson进行json序列化和反序列化?
  • springboot 通过HttpMessageConverters 消息转换器通过jackson将java对象转化为json字符串。如果项目里包含多个json工具包比如jackson ,fastjson,那么就会各个年级对象的内容选择一个合适的去转换为json。
  • 这是HttpMessageConverters 消息转换器所处的位置,所以项目里采用那个json工具由该类决定。
  • springboot默认使用jackson,springboot默认集成的就是jackson。
  • 指定使用fastJson的一种做法:
     
    1.  
    2. public class SpringBootMain extends SpringBootServletInitializer implements WebApplicationInitializer {

    3. @Bean

    4. public HttpMessageConverters fastJsonHttpMessageConverters() {

    5. // 1.定义一个converters转换消息的对象

    6.  
    7. FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

    8. // 2.添加fastjson的配置信息,比如: 是否需要格式化返回的json数据

    9.  
    10. FastJsonConfig fastJsonConfig = new FastJsonConfig();

    11. fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

    12. // 3.在converter中添加配置信息

    13. fastConverter.setFastJsonConfig(fastJsonConfig);

    14. // 4.将converter赋值给HttpMessageConverter

    15. HttpMessageConverter<?> converter = fastConverter;

    16. // 5.返回HttpMessageConverters对象

    17. return new HttpMessageConverters(converter);

    18. }

    19. }

    参考:

  • https://blog.csdn.net/m0_37948170/article/details/85327093

猜你喜欢

转载自blog.csdn.net/JacksonKing/article/details/89923271