SpringBoot 返回JSON格式数据

第一步:项目添加fastjson 依赖

<!-- fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>

第二步:配置fastjson 

第一种方法:

Ø  启动类继承WebMvcConfigurerAdapter

Ø  覆盖方法configureMessageConverters

package com.zzg.springboot;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

/**
 * 1.使用fastjson,需要继承WebMvcConfigurerAdapter,覆盖configureMessageConverters方法
 * 
 * @author zzg
 * 
 */
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {

   public static void main(String[] args) {
      // 启动spring容器
      SpringApplication.run(App.class, args);
   }

   @Override
   public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
      super.configureMessageConverters(converters); // 创建fastjson对象
      //创建convert消息转换对象
      FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

      // 添加fastjosn配置信息,设置是否需要格式化
      FastJsonConfig confg = new FastJsonConfig();
      confg.setSerializerFeatures(SerializerFeature.PrettyFormat);
      //添加配置信息到消息对象
      converter.setFastJsonConfig(confg);
      
      converters.add(converter);
   }

}

第二种方法:(推荐)

通过bean注入一个消息对象转换对象:HttpMessageConverters

package com.zzg.config;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
public class SpringMVCConfig {
	/**
	 * 使用bean方式注入fastjson解析器
	 *
	 * @return
	 */
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {
		// 创建fastjson对象
		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

		FastJsonConfig confg = new FastJsonConfig();
		// 设置是否需要格式化
		confg.setSerializerFeatures(SerializerFeature.PrettyFormat);
		converter.setFastJsonConfig(confg);
		return new HttpMessageConverters(converter);
	}

}

猜你喜欢

转载自blog.csdn.net/zhouzhiwengang/article/details/90399825