Gson与Spring Boot

栏目: Java · 发布时间: 5年前

内容简介:在本文中,我们将学习如何在Spring Boot中使用Google Gson。Spring Boot是一个具有某些默认值的智能系统,它具有Gson的自动配置功能。一旦发现Gson在类路径上,Spring Boot将自动配置Gson bean。它还在application.properties文件中提供了几个Gson特定属性。

在本文中,我们将学习如何在Spring Boot中使用Google Gson。 Gson 是一个开源 Java 库,用于将Java对象序列化和反序列化为JSON。

Spring Boot 使用Jackson作为默认库,将Java对象序列化和反序列化为JSON。如果 在应用程序中添加“ spring-boot-starter ” ,它将包含在您的类路径中。这很棒,但有时您可能希望使用其他API,而不是 Spring Boot自动配置中 可用的API 。在本文中,我们将介绍使用Gson和Spring Boot的步骤。

Spring Boot是一个具有某些默认值的智能系统,它具有Gson的自动配置功能。一旦发现Gson在类路径上,Spring Boot将自动配置Gson bean。它还在application.properties文件中提供了几个Gson特定属性。

1. Maven依赖

我们配置的第一步是在我们的pom.xml文件中添加Gson依赖项。这就是我们的pom.xml文件的样子:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version> <!-- check latest version <b>for</b> GSON -->
</dependency>

通过上面的配置,Spring Boo创建了一个具有合理默认值的Gson bean。Spring提供了一个 GsonHttpMessageConverter ,它可以使用Google Gson库读写JSON。

1.1使用Gson作为默认Mapper

我们将Gson包含在类路径中,但我们需要使用application.properties文件将Gson设置为首选映射器。

spring.http.converters.preferred-json-mapper=gson #Preferred JSON mapper to use <b>for</b> HTTP message conversion.

如果您没有设置首选的json映射器,您可能会碰到 org.springframework.http.converter.HttpMessageNotWritableException.

1.2 Gson配置

Spring Boot为Gson配置提供了几个属性。这是列表参考:

# 序列化日期对象时使用的格式。
spring.gson.date-format= 

# 是否禁用HTML字符转义,如“<”、“>”等。
spring.gson.disable-html-escaping= 

# 是否在序列化期间排除内部类。
spring.gson.disable-<b>inner</b>-<b>class</b>-serialization= 

# 是否启用复杂映射键(即非原语)的序列化。
spring.gson.enable-complex-map-key-serialization=

# 是否排除所有没有“expose”注释的字段进行序列化或反序列化。
spring.gson.exclude-fields-without-expose-annotation= 

# 在序列化和反序列化期间应用于对象字段的命名策略。
spring.gson.field-naming-policy= 

# 是否通过在输出前添加一些特殊文本来生成不可执行的JSON。
spring.gson.generate-non-executable-json= 

# 对于解析不符合RFC 4627的JSON是否宽容。
spring.gson.lenient= 

# 长类型和长类型的序列化策略。
spring.gson.<b>long</b>-serialization-policy= 

# 是否输出适合漂亮打印页面的序列化JSON。
spring.gson.pretty-printing=

# 是否序列化空字段。
spring.gson.serialize-nulls= 

2.排除Jackson的依赖

如果您将Gson用作默认库,请从类路径中删除Jackson。有两种方法可以将它从类路径中排除

2.1使用Maven

最简单的方法是使用您的排除标记pom.xml。Spring Boot将Jackson添加为Web启动器的一部分,我们所需要的只是将其排除在Web启动器中。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- Exclude the <b>default</b> Jackson dependency -->
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-json</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
</dependencies>

2.1使用Exclude属性

第二种方法是使用带有@EnableAutoConfiguration或 @SpringBootApplication  的exclude属性

@SpringBootApplication(exclude = {JacksonAutoConfiguration.<b>class</b>})
<b>public</b> <b>class</b> GsonSpringBootApplication {

    <b>public</b> <b>static</b> <b>void</b> main(String[] args) {
        SpringApplication.run(GsonSpringBootApplication.<b>class</b>, args);
    }
}

使用此选项,您可以跳过设置,  spring.http.converters.preferred-json-mapper因为Spring Boot只配置一个映射器

3.使用HttpMessageConverters自定义

要在Spring Boot应用程序中自定义Gson映射器的行为,您可以扩展  WebMvcConfigurerAdapter 以获取 带有SpringHttp消息转换器 。我们将举例说明我们要为JSON转换器自定义日期格式。

@Configuration
<b>public</b> <b>class</b> ApplicationConfig <b>extends</b> WebMvcConfigurerAdapter {

    @Override
    <b>public</b> <b>void</b> configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(customGsonHttpMessageConverter());
        <b>super</b>.configureMessageConverters(converters);
    }

    <b>private</b> GsonHttpMessageConverter customGsonHttpMessageConverter() {
        Gson gson = <b>new</b> GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .setDateFormat(<font>"yyyy'-'MM'-'dd'T'HH':'mm':'ss'"</font><font>)
                .create();

        GsonHttpMessageConverter gsonMessageConverter = <b>new</b> GsonHttpMessageConverter();
        gsonMessageConverter.setGson(gson);

        <b>return</b> gsonMessageConverter;
    }
}
</font>

4.单元测试

让我们设置一个小单元测试用例来测试Gson转换器。

@RunWith(SpringRunner.<b>class</b>)
@SpringBootTest
<b>public</b> <b>class</b> GsonSpringBootApplicationTests {

    <b>private</b> Product product;

    @Before
    <b>public</b> <b>void</b> setup(){
        product =<b>new</b>  Product(<font>"123"</font><font>,</font><font>"Demo Product"</font><font>,123);
    }

    @Test
    <b>public</b> <b>void</b> simpleGsonTest() throws JSONException {
        String expected = </font><font>"{\n"</font><font> +
                </font><font>"\"code\": \蕋\",\n"</font><font> +
                </font><font>"\"name\": \"Demo Product\",\n"</font><font> +
                </font><font>"\"price\": 123\n"</font><font> +
                </font><font>"}"</font><font>;

        Gson gson = <b>new</b> GsonBuilder().create();
        String data= gson.toJson(product);

        JSONAssert.assertEquals(expected,data,false);
    }

    @Test
    <b>public</b> <b>void</b> errorGsonTest() throws JSONException {
        String expected = </font><font>"{\n"</font><font> +
                </font><font>"\"code\": \㓱\",\n"</font><font> +
                </font><font>"\"name\": \"Demo Product\",\n"</font><font> +
                </font><font>"\"price\": 123\n"</font><font> +
                </font><font>"}"</font><font>;

        Gson gson = <b>new</b> GsonBuilder().create();
        String data= gson.toJson(product);

        JSONAssert.assertEquals(expected,data,false);
    }
}
</font>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

One Click

One Click

Richard L. Brandt / Portfolio Hardcover / 2011-10-27 / 25.95

An insightful look at how Amazon really works and how its founder and CEO makes it happen. Amazon's business model is deceptively simple: make online shopping so easy and convenient that customers ......一起来看看 《One Click》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具