Spring Boot fastjson使用

1.添加依赖

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

2.配置fastjson的HttpMessageConverter

@Configuration
public class MyFastJsonConfig {
    @Bean
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd");
        config.setCharset(Charset.forName("UTF-8"));
        config.setSerializerFeatures(
                SerializerFeature.WriteClassName,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty
                );
        converter.setFastJsonConfig(config);
        return  converter;
    }
}

3.实体类

public class Book {
    private String name;
    private String autor;
    
    protected   Float price;

    private Date publicationDate;

    public Date getPublicationDate() {
        return publicationDate;
    }

    public Float getPrice() {
        return price;
    }

    public String getName() {
        return name;
    }

    public String getAutor() {
        return autor;
    }

    public void setAutor(String autor) {
        this.autor = autor;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public void setPublicationDate(Date publicationDate) {
        this.publicationDate = publicationDate;
    }
}

4.在application.properties中添加配置防止出现中文乱码

spring.http.encoding.force-response=true

5.控制器

@Controller
public class BookController {
    @GetMapping("/book")
    @ResponseBody
    public  Book book(){
        Book book = new Book();
        book.setAutor("罗贯中");
        book.setName("三国演义");
        book.setPrice(30f);
        book.setPublicationDate(new Date());
        return book;
    }
}

6.访问测试

发布了255 篇原创文章 · 获赞 39 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/kangguang/article/details/104268211