【Springboot学习 | 3】配置使用FastJson返回Json视图

一、添加依赖

fastJson为阿里巴巴2017年开始发布并维护,目的是将fastJson加入到SpringBoot等项目内,配置json返回视图使用fastJson解析。

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.59</version>
        </dependency>

二、添加FastJson配置

在前面一文的基础上:【springboot学习 | 2】jpa+mysql8.0增删改查
创建一个FastJsonConfiguration配置信息类,与Application同级:
在这里插入图片描述
配置类解释:

  1. @Configuration:让SpringBoot自动加载类内的配置
  2. 继承了WebMvcConfigurationSupport是SpringBoot内部提供专门处理用户自行添加的配置,里面不仅仅包含了修改视图的过滤还有其他很多的方法,包括后面可能会用到的拦截器,过滤器,Cors配置等.
  3. configureMessageConverters():修改自定义消息转换器
  4. SerializerFeature:过滤
    • DisableCircularReferenceDetect,//消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
    • WriteMapNullValue//是否输出值为null的字段,默认为false。

测试版本:
FastJsonConfiguration.java

package com.springboot.three;

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.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;


@Configuration
public class FastJsonConfiguration extends WebMvcConfigurationSupport {
    /**
     * 修改自定义消息转换器
     * @param converters 消息转换器列表
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
    {
        //调用父类配置
        super.configureMessageConverters(converters);
        //创建消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //创建配置类
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //返回内容的过滤
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue//,
                //SerializerFeature.WriteNullStringAsEmpty
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //将fastjson添加到视图消息转换器列表内
        converters.add(fastConverter);
    }
}

三、测试

将数据库设置一个值为空:
在这里插入图片描述
浏览器查询:http://127.0.0.1:8080/user/list ,测试结果:
在这里插入图片描述
修改FastJson配置代码:
在这里插入图片描述
再运行Springboot主函数,浏览器测试:
在这里插入图片描述

补充

问题描述
今天在用postman进行测试时,控制台报出以下错误:
java.lang.IllegalArgumentException: Content-Type cannot contain wildcard type '*'

原因分析:
升级到最新版本的fastjson以后报的错,发现fastjson从1.1.41升级到1.2.59之后,请求报错:
json java.lang.IllegalArgumentException: ‘Content-Type’ cannot contain wildcard type ‘*’

原因是在1.1.41中,FastJsonHttpMessageConverter初始化时,设置了MediaType。

public FastJsonHttpMessageConverter(){
    super(new MediaType("application", "json", UTF8), new MediaType("application", "*+json", UTF8));
}

而在1.2.59中,设置的MediaType为‘/’,即:

public FastJsonHttpMessageConverter() {
    super(MediaType.ALL);  // */*
}

后续在org.springframework.http.converter.AbstractHttpMessageConverter.write过程中,又要判断Content-Type不能含有通配符,这应该是一种保护机制,并强制用户自己配置MediaType。

参考:Spring Boot配置FastJson报错’Content-Type’ cannot contain wildcard type ‘*’

解决办法

完整的FastJsonConfiguration:

package com.springboot.three;

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.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.ArrayList;
import java.util.List;


@Configuration//@Configuration让SpringBoot自动加载类内的配置
//WebMvcConfigurationSupport是SpringBoot内部提供专门处理用户自行添加的配置,
// 里面不仅仅包含了修改视图的过滤还有其他很多的方法,包括后面可能会用到的拦截器,过滤器,Cors配置等.
public class FastJsonConfiguration extends WebMvcConfigurationSupport {
    /**
     * 修改自定义消息转换器
     * @param converters 消息转换器列表
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
    {
        //调用父类配置
        super.configureMessageConverters(converters);
        //创建消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        //升级最新版本需加=================================================
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);

        //创建配置类
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //返回内容的过滤
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,//消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
                //SerializerFeature.WriteMapNullValue,//是否输出值为null的字段,默认为false。
                SerializerFeature.WriteNullStringAsEmpty//数据库字段设置了NULL时,前端返回json为""替代null
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //将fastjson添加到视图消息转换器列表内
        converters.add(fastConverter);
    }
}

postman测试:无误!
在这里插入图片描述

总结

json为空时,在前端调用会显示null效果不好,或者js语言报错,都是很不便的;
fastjson则可以避免这种情况。

?源码地址:
https://github.com/cungudafa/SpringBoot

首先,需要在 `pom.xml` 文件中添加以下依赖: ```xml <dependencies> <!-- Spring Boot Web Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Test Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Apache HttpClient 5 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient5</artifactId> <version>5.1.2</version> </dependency> <!-- Fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> </dependencies> ``` 然后,创建一个 `RestTemplate` 的 Bean: ```java import org.apache.hc.client5.http.async.methods.SimpleHttpRequests; import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder; import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer; import org.apache.hc.core5.concurrent.FutureCallback; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.Method; import org.apache.hc.core5.http.nio.support.BasicRequestProducer; import org.apache.hc.core5.http.nio.support.BasicResponseConsumer; import org.apache.hc.core5.http.protocol.HttpContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.client.HttpComponentsAsyncClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.AsyncRestTemplate; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.Future; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); restTemplate.setInterceptors(Collections.singletonList(new RestTemplateHeaderModifierInterceptor(headers))); // 设置请求和响应的消息转换器 MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN)); restTemplate.setMessageConverters(Collections.singletonList(converter)); // 设置请求工厂 HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setConnectTimeout(10000); requestFactory.setReadTimeout(10000); restTemplate.setRequestFactory(requestFactory); return restTemplate; } @Bean public AsyncRestTemplate asyncRestTemplate() { AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(); // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); asyncRestTemplate.setInterceptors(Collections.singletonList(new RestTemplateHeaderModifierInterceptor(headers))); // 设置请求和响应的消息转换器 MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN)); asyncRestTemplate.setMessageConverters(Collections.singletonList(converter)); // 设置请求工厂 HttpComponentsAsyncClientHttpRequestFactory requestFactory = new HttpComponentsAsyncClientHttpRequestFactory(); requestFactory.setConnectTimeout(10000); requestFactory.setReadTimeout(10000); asyncRestTemplate.setAsyncRequestFactory(requestFactory); return asyncRestTemplate; } private static class RestTemplateHeaderModifierInterceptor implements org.springframework.http.client.ClientHttpRequestInterceptor { private final HttpHeaders headers; public RestTemplateHeaderModifierInterceptor(HttpHeaders headers) { this.headers = headers; } @Override public org.springframework.http.client.ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { headers.forEach((key, value) -> request.getHeaders().put(key, value)); return execution.execute(request, body); } } } ``` 其中,`RestTemplateHeaderModifierInterceptor` 是用来设置请求头的拦截器,`MappingJackson2HttpMessageConverter` 是用来转换请求和响应消息的消息转换器,`HttpComponentsClientHttpRequestFactory` 和 `HttpComponentsAsyncClientHttpRequestFactory` 是用来配置请求工厂的。 在上面的代码中,我同时定义了同步和异步的 `RestTemplate`,你可以根据需要选择其中一个。 使用示例: ```java import com.alibaba.fastjson.JSONObject; import org.apache.http.entity.ContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/test") public class TestController { @Autowired private RestTemplate restTemplate; @GetMapping("/sync") @ResponseBody public String testSync() { String url = "https://jsonplaceholder.typicode.com/todos/1"; ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class); return responseEntity.getBody(); } @GetMapping("/async") @ResponseBody public String testAsync() throws Exception { String url = "https://jsonplaceholder.typicode.com/todos/1"; Future<ResponseEntity<String>> future = restTemplate.exchange(url, HttpMethod.GET, null, String.class); ResponseEntity<String> responseEntity = future.get(); return responseEntity.getBody(); } } ``` 上面的示例中,我使用 `RestTemplate` 发送了一个 GET 请求,请求的 URL 是 `https://jsonplaceholder.typicode.com/todos/1`,并且指定了响应消息的类型为 `String`。如果你需要发送 POST 请求,只需要将 `HttpMethod.GET` 改为 `HttpMethod.POST`,并且设置请求体即可。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值