博客
关于我
jackson学习之九:springboot整合(配置文件)
阅读量:419 次
发布时间:2019-03-06

本文共 5052 字,大约阅读时间需要 16 分钟。

Spring Boot与Jackson的完美结合:配置与实战示例

在开发Spring Boot应用时,Jackson作为默认的JSON处理工具,能够通过简单的配置实现对JSON数据的高效序列化与反序列化。本文将详细介绍如何在Spring Boot项目中配置Jackson,以及通过实际案例展示其应用效果。

Jackson配置概述

在Spring Boot项目中,Jackson的配置可以通过两种方式实现:一种是通过propertiesyml文件,另一种是通过配置类实现。在本文中,我们将以properties文件方式进行配置,并通过实际案例进行验证。

配置文件的创建

首先,我们需要在项目的resources目录下创建一个application.yml文件,配置Jackson的相关参数。以下是示例配置内容:

spring:  jackson:    date-format: yyyy-MM-dd HH:mm:ss    serialization:      indent_output: true      fail_on_empty_beans: true    deserialization:      fail_on_unknown_properties: false      defaultPropertyInclusion: NON_EMPTY    parser:      allow_unquoted_control_chars: true      allow_single_quotes: true

配置文件的验证

在完成上述配置后,我们可以通过以下步骤验证其有效性:

  • 默认配置测试:运行Spring Boot应用,访问http://localhost:8080/swagger-ui.html,观察 Swagger文档中的JSON字段格式,确保JsonProperty注解已成功生效。

  • 实际接口测试:通过浏览器访问http://localhost:8080/jsonproperty/serialization,查看返回的JSON格式,确认日期格式化和其他配置是否生效。

  • 配置类的方式

    除了通过yml文件配置Jackson,还可以通过配置类的方式实现。这种方式适用于需要更详细控制Jackson行为的场景。以下是一个典型的配置类示例:

    import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.ser.SerializerAnnotation;import com.fasterxml.jackson.databind.ser.SerializerReplacement;import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;@Configuration@EnableSwagger2public class SwaggerConfig {    private static final Logger logger = LoggerFactory.getLogger(SwaggerConfig.class);    @Autowired    private ObjectMapper mapper;    @Bean    public Docket createRestApi() {        return new Docket(DocumentationType.SWAGGER_2)                .apiInfo(apiInfo())                .tags(new Tag("JsonPropertySerializationController", "JsonProperty相关测试"))                .select()                .apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.springbootproperties.controller"))                .paths(PathSelectors.any())                .build();    }    private ApiInfo apiInfo() {        return new ApiInfoBuilder()                .title("SpringBoot整合Jackson(基于配置文件)")                .contact(new Contact("程序员欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))                .version("1.0")                .description("API 描述")                .build();    }}

    Bean类的序列化与反序列化

    为了验证Jackson的配置是否有效,我们可以创建一个Bean类,并通过注解控制其序列化和反序列化行为。以下是一个典型的Bean类示例:

    import com.fasterxml.jackson.annotation.JsonProperty;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import java.util.Date;@ApiModel(description = "JsonProperty注解测试类")public class Test {    @ApiModelProperty(value = "私有成员变量")    @JsonProperty(value = "json_field0", index = 1)    private Date field0 = new Date();    @ApiModelProperty(value = "来自get方法的字符串")    @JsonProperty(value = "json_field1", index = 0)    public String getField1() {        return "111";    }    @Override    public String toString() {        return "Test{" +                "field0=" + field0 +                '}';    }}

    实际应用示例

    以下是一个简单的Controller类,展示了如何在Spring Boot应用中使用上述配置:

    import com.bolingcavalry.springbootproperties.bean.Test;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/jsonproperty")@Api(tags = {"JsonPropertySerializationController"})public class JsonPropertySerializationController {    private static final Logger logger = LoggerFactory.getLogger(JsonPropertySerializationController.class);    @Autowired    private ObjectMapper mapper;    @ApiOperation(value = "测试序列化", notes = "测试序列化")    @RequestMapping(value = "/serialization", method = RequestMethod.GET)    public Test serialization() throws JsonProcessingException {        Test test = new Test();        logger.info(mapper.writeValueAsString(test));        return test;    }    @ApiOperation(value = "测试反序列化", notes = "测试反序列化")    @RequestMapping(value = "/deserialization", method = RequestMethod.PUT)    public String deserialization(@RequestBody Test test) {        return test.toString();    }}

    总结

    通过以上配置和示例,我们可以清晰地看到Spring Boot与Jackson的无缝结合。配置文件能够轻松地进行JSON处理的各种设置,而通过注解则可以对Bean类的序列化和反序列化有细致的控制。这种结合使得在开发RESTful API时更加高效和可靠。

    转载地址:http://qqtkz.baihongyu.com/

    你可能感兴趣的文章
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>