springboot2------自定义消息转换器

5、自定义消息转换器

当我们想自定义消息转换器时,也不要着急,springboot中也定义了对应的接口,只要我们实现该接口就行了

public interface HttpMessageConverter<T> {
   boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

   boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

   List<MediaType> getSupportedMediaTypes();

   default List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
      return (canRead(clazz, null) || canWrite(clazz, null) ?
            getSupportedMediaTypes() : Collections.emptyList());
   }

   T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
         throws IOException, HttpMessageNotReadableException;

   void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
         throws IOException, HttpMessageNotWritableException;

}

下面是具体的实现类:

package com.boot.config;

import com.boot.pojo.People;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class PeopleMessageConvert implements HttpMessageConverter<People>  {

    //是否能够读取,意思就是能不能读取网络上的数据类型
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    //表示是否能够将数据改为对应格式
    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return true;
    }

    //获取支持的媒体类型
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/xyj-maiDang");
    }

    //读取
    @Override
    public People read(Class<? extends People> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    //写出
    @Override
    public void write(People people, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

        String message=people.toString();
        OutputStream out = outputMessage.getBody();
        out.write(message.getBytes());
    }
}

关于媒体类型的自定义:

 public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/xyj-maiDang");
    }

必须是按* / * 的格式,原因如下:
在这里插入图片描述

看到第6个就什么都明白了,是不是

然后就是将自定义的消息转换器添加到容器中,

//来自WebMvcConfigurer.java
default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
}

default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
}

这里我们使用的是extendMessageConverters方法因为这个方法是用于扩展的,他不会改变原来已经存在的转换器,

configureMessageConverters是配置转换器,这样会使容器中以前配置的转换器删除

package com.boot.config;

import com.boot.pojo.People;
import com.boot.pojo.Pet;
import org.springframework.beans.PropertyEditorRegistrySupport;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

import java.util.List;

//
@Configuration()
//@EnableConfigurationProperties(Pet.class)
public class MyConfig {

//    @Bean
//    public Pet cat(){
//        return new Pet();
//    }
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
                converters.add(new PeopleMessageConvert());
            }

        };
    }


}

然后debug就可以看见我们自定义的转换器已经被添加进去了

在这里插入图片描述

学习springboot,可以多看看WebMvcAutoConfiguration.java这个类,我们所需要的很多扩展都可以参考这个

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个基于 Spring 的轻量级框架,可以快速搭建基于 Spring 的应用程序。而 Fastjson 是一个高性能的 Java 序列化和反序列化库,可以处理复杂的 JSON 数据。 如果想要在 Spring Boot自定义 Fastjson 作为 JSON 消息转换器,可以按照以下步骤进行操作: 首先,在 pom.xml 文件中引入 Fastjson 的依赖,可以通过以下代码来添加依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> ``` 然后,在 Spring Boot 的配置类中配置 Fastjson 作为 JSON 消息转换器。可以通过以下代码来实现: ```java @Configuration public class FastjsonConfig { @Bean public HttpMessageConverters fastjsonHttpMessageConverter() { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); converter.setDefaultCharset(Charset.forName("UTF-8")); List<MediaType> supportedMediaTypes = new ArrayList<>(); supportedMediaTypes.add(MediaType.APPLICATION_JSON); converter.setSupportedMediaTypes(supportedMediaTypes); FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.PrettyFormat); converter.setFastJsonConfig(config); return new HttpMessageConverters(converter); } } ``` 最后,在 Spring Boot 的主类中加上 @EnableWebMvc 注解,启用自定义的 JSON 消息转换器。 通过以上步骤,就成功地使用了 Spring Boot 自定义 Fastjson 作为 JSON 消息转换器。这样可以方便地处理 JSON 数据,提升了系统的性能和效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值