英雄【配置json和xml数据转换】
英雄介绍:
Spring Boot依然遵循MVC架构,采用RESTful API交互,返回的数据常常转换为JSON或XML格式直接写入HTTP响应的body中。最常见的就是使用注解@ResponseBody,它会根据请求头信息来判断消息转换器,将Java对象转换为json或xml格式的数据返回。
package com.linx.one.myspringboot.vo;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.*;
import java.util.Date;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@JacksonXmlRootElement(localName = "用户")
public class UserVO {
@JacksonXmlProperty(localName = "id")
private int id;
@JacksonXmlProperty(localName = "名称")
private String name;
@JacksonXmlProperty(localName = "年龄")
private int age;
@JacksonXmlProperty(localName = "生日")
private Date birthday;
}
技能一:JSON数据转换
@GetMapping(value = "/getJson",produces = MediaType.APPLICATION_JSON_VALUE)
@SystemLog(name="getUserVoJson方法")
public UserVO getUserVoJson(){
UserVO userVO = new UserVO();
userVO.setAge(24);
userVO.setId(1);
userVO.setName("linx");
userVO.setBirthday(new Date());
return userVO;
}
返回的json的数据可以使用下面的配置修改日期格式
package com.linx.one.myspringboot.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
@Configuration
public class WebMvcConfig {
@Bean
public ObjectMapper getObjectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"));
return objectMapper;
}
}
技能二:XML数据转换
需要导入xml转换器的依赖
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
@GetMapping(value = "/getXML",produces = MediaType.APPLICATION_XML_VALUE)
@SystemLog(name="getUserVoXML方法")
public UserVO getUserVoXML(){
UserVO userVO = new UserVO();
userVO.setAge(24);
userVO.setId(1);
userVO.setName("linx");
userVO.setBirthday(date);
return userVO;
}
技能三:自定义转换器
package com.linx.one.myspringboot.converter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.Charset;
public class MessageConverter extends AbstractHttpMessageConverter {
public MessageConverter(){
super(new MediaType("application","json",Charset.forName("UTF-8")));
}
@Override
protected boolean supports(Class clazz) {
return true;
}
@Override
protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
return temp;
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
StreamUtils.copy(o.toString(),Charset.forName("UTF-8"),outputMessage.getBody());
}
}
一、通过Spring注入的方式
package com.linx.one.myspringboot.config;
import com.linx.one.myspringboot.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebMvcConfig {
@Bean
public MessageConverter messageConverter(){
MessageConverter messageConverter = new MessageConverter();
return messageConverter;
}
}
二、通过实现WebMvcConfigurer接口
package com.linx.one.myspringboot.config;
import com.linx.one.myspringboot.converter.MessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
public void configureMessageConverters(List<HttpMessageConverter<?> converters>){
MessageConverter messageConverter = new MessageConverter();
converters.add(messageConverter);
}
}
三、通过继承WebMvcConfigurationSupport,并重写configureMessageConverters方法
package com.linx.one.myspringboot.config;
import com.linx.one.myspringboot.converter.MessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
public void configureMessageConverters(List<HttpMessageConverter<?> converters>){
MessageConverter messageConverter = new MessageConverter();
converters.add(messageConverter);
}
}
技能四:使用Fastjson转换器
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
通过注入的方式将Jackson替换成Fastjson
package com.linx.one.myspringboot.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebMvcConfig {
@Bean
public HttpMessageConverter fastJsonHttpMessageConverter(){
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
//是否将结果格式化,默认是false,配置后则格式化
SerializerFeature.PrettyFormat,
//输出值是否为NULL的字段,默认为false,配置后则输入map中的空字段
SerializerFeature.WriteMapNullValue,
//将String类型的NULL返回""
SerializerFeature.WriteNullStringAsEmpty,
//将Number类型的NULL返回0
SerializerFeature.WriteNullNumberAsZero,
//将List类型的空集合NULL返回[]
SerializerFeature.WriteNullListAsEmpty,
//将Boolean类型的NULL返回false
SerializerFeature.WriteNullBooleanAsFalse,
//避免循环引用
SerializerFeature.DisableCircularReferenceDetect
);
converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8"));
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(mediaTypes);
return converter;
}
}