游戏【spingboot框架】——英雄【配置json和xml数据转换】

英雄【配置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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值