Spring Boot 整合之Fastjson

Spring Boot 整合Fastjson

1. 在pom.xml中导入Fastjson依赖

<!--使用json对象-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.49</version>
</dependency>

2. 创建管理类WebConfig

package com.wyp.util;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;

public class WebConfig {

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;

        return new HttpMessageConverters(converter);

    }

}

3. 创建实体类和数据库表,这里自己写

4. 创建Controller

package com.wyp.controller;

import com.wyp.pojo.TTest;
import com.wyp.service.TTestService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * Spring Boot整合fastjson
 */
@Controller
@RequestMapping("fastjson")
public class TTestController2 {

    @Resource
    private TTestService tTestService;

    @ResponseBody
    @RequestMapping(value = "/fastjson")
    public TTest test(){
        TTest tTest = tTestService.getTTestListById(2);
        System.out.println(tTest);
        return tTest;
    }

}

5. 运行SpringbootLpplication,结果如下

注:如果有乱码问题,在Controller的方法中如下加上produces

 @RequestMapping(value = "/test",produces="text/html;charset=UTF-8")

我这里地址路径之所以有个springboot,是因为我在application.properties中加了一个地址,如下,如果不加的话就可以去掉访问地址中的springboot

server.servlet.context-path=/springboot

猜你喜欢

转载自blog.csdn.net/yi_yu_ya/article/details/83931088