SpringBoot整合web放回json数据的方法

本文介绍了如何在SpringBoot项目中返回JSON数据。默认情况下,SpringBoot通过web依赖中的jackson-databind处理JSON。此外,还展示了如何自定义类型转换器,以使用Gson。添加Gson依赖后,需要配置HttpMessageConverter以处理日期格式化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用默认

我们知道,要整合web项目,就要添加web依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

在这个依赖中默认加入了jackson-databind作为JSON处理器,所以导入了web的依赖就不需要再添加额外的JSON处理器就能放回一个JSON数据了;

 @RequestMapping("test")
    @ResponseBody
    //放回json数据
    public student getString(){
        return new student("小明",20);
    }

页面显示

在这里插入图片描述

这是通过Spring中默认的提供的MappingJackson2HttpMassageConverter来实现的,当然开发者也可以通过自定义json转换器;

自定义类型转换器:

常见的JSON处理器除了jackson-databind之外,还有Gson和fastjson这里针对常见的用法分别举例:

使用Gson

Gson时Google的一个开源的JSON解析框架,使用Gson,需要先除去默认的jackson-databind,然后加入Gson依赖:

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>

由于Spring Boot中默认提供了Gson的自动类型转换类GsonHttpMessageConverterConfiguration,因此Gson的依赖添加成功后可以象jackson-databing那样直接使用Gson。但想对日期数据进行格式化还需要自定义HttpMessageConverter;

GsonHttpMessageConverterConfiguration的一段源码如下:

 		@Bean
        @ConditionalOnMissingBean
        GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
            GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
            converter.setGson(gson);
            return converter;
        }

@ConditionalOnMissingBean注解表示当项目中没有提供GsonHttpMessageConverter时才会使用默认的GsonHttpMessageConverter,所以我们只需要提供一个GsonHttpMessageConverter就可以了:

@Configuration
public class GsonConfig {
    @Bean
    GsonHttpMessageConverter gsonHttpMessageConverter(){
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat("yyyy/MM/dd");//设置日期格式
        builder.excludeFieldsWithModifiers(Modifier.PROTECTED);//将修饰符为protected的字段过滤掉
        Gson gson = builder.create();
        converter.setGson(gson);
        return converter;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值