springbootcontroller对象属性转换:⾃定义json消息处理器
背景
我们后端写接⼝的时候可能会碰到属性字段转换的情况,⽐如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.fig.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import t.annotation.Bean;
import t.annotation.Configuration;
json转换对象import Ordered;
import org.springframework.http.MediaType;
import org.verter.HttpMessageConverter;
import org.verter.StringHttpMessageConverter;
import org.springframework.fig.annotation.ContentNegotiationConfigurer;
import org.springframework.fig.annotation.ResourceHandlerRegistry;
import org.springframework.fig.annotation.ViewControllerRegistry;
import org.springframework.fig.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就失效了。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论