版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wm5920/article/details/84954820
背景
我们后端写接口的时候可能会碰到属性字段转换的情况,比如user_name转成userName,这个时候手动写get set肯定很不方便,这个时候注解神器就可以用了,常用的有两种JSONField与JsonProperty。
具体使用
JSONField与JsonProperty出自两个json框架,前者出自alibaba,后者出自fasterxml。alibaba的一般默认推荐,性能高使用方便,但是fasterxml是springmvc默认使用的。所以如果偷懒或者没啥特别要求的话就使用JsonProperty就可以转换了。
接参对象
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class BigVo {
@JsonProperty(value = "bb")
private String name;
@JSONField(name = "bb1")
private String name1;
controller方法
@RequestMapping(value="/hello", method = RequestMethod.POST)
public BigVo index1(@RequestBody BigVo vo) {
return vo;
}
请求数据
{"bb":"1","bb1":"2"}
默认情况下JsonProperty生效,JSONField没啥效果。但是如果不自定义处理器,返回的属性是没办法自动转换的哦。
为了能使用JSONField而且返回的属性也能自动转换,下面就来介绍自定义json处理器!
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
// 自定义消息转化器的第二种方法
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
converters.add(converter);
}
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
//1.需要定义一个convert转换消息的对象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//2:添加fastJson的配置信息;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//4.在convert中添加配置信息.
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
return new HttpMessageConverters(converter);
}
}
加上上面配置后即可愉快的使用JSONField了,当然这个时候JsonProperty就失效了。