2个注解都是为了解决json字符串的某些属性名和JavaBean中的属性名匹配不上的问题。
例子,不使用注解的情况
@Data
public class Routine {private Integer TTS_voice;}
@PostMapping("/test8")public Routine test8(@RequestBody Routine routine){return routine;}
传递参数为null并且返回的结果字段名也不一致。(命名原因jackson会自动帮你转换)
1.@JsonProperty
该注解为jackson包下的,在starter-web启动器下已经存在。
使用方法,在bean属性或方法上加上该注解
@Data
public class Routine {@JsonProperty("TTS_voice")private Integer TTS_voice;}
测试(因为springboot默认的转换方式就是jackson所以不需要做配置)
在使用自定义getset方法时发现会出现重复字段,查看编译过后的@lombok发现生成的方法与自定义的无区别但是不会出现重复字段。
public class Routine {@JsonProperty("TTS_voice")private Integer TTS_voice;public Integer getTTS_voice() {return TTS_voice;}public void setTTS_voice(Integer TTS_voice) {this.TTS_voice = TTS_voice;}
}
出现重复字段解决办法,@JsonProperty改为加在get方法上
public class Routine {private Integer TTS_voice;@JsonProperty("TTS_voice")public Integer getTTS_voice() {return TTS_voice;}public void setTTS_voice(Integer TTS_voice) {this.TTS_voice = TTS_voice;}
}
2. @JSONField
该注解为fastjson包下的,导包
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.24</version></dependency>
启动类配置fastjson转换(如果仅仅是内部使用转换json字符串则不需要配置)
@Beanpublic HttpMessageConverters fastJsonHttpMessageConverters(){//1、先定义一个convert转换消息的对象FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();//2、添加fastjson的配置信息,比如是否要格式化返回的json数据;FastJsonConfig fastJsonConfig=new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);//附加:处理中文乱码List<MediaType> fastMedisTypes = new ArrayList<MediaType>();fastMedisTypes.add(MediaType.APPLICATION_JSON_UTF8);fastConverter.setSupportedMediaTypes(fastMedisTypes);//3、在convert中添加配置信息fastConverter.setFastJsonConfig(fastJsonConfig);HttpMessageConverter<?> converter=fastConverter;return new HttpMessageConverters(converter);}
使用方法与@JsonProperty一致
@Data
public class Routine {@JSONField(name = "TTS_voice")private Integer TTS_voice;}
需要注意的是在使用这2个注解进行转换时必须使用相应的方法否则不起作用(fastjson、jackson)
fastjson忽略属性注解为@JSONField(serialize = false)
jackson忽略属性注解为@JsonIgnore