Welcome to my GitHub

Here classification and summary of xinchen all original (including supporting source code) : github.com/zq2599/blog…

Series of articles

  • One of Jackson’s lessons: Basic information
  • Jackson Learning 2: Jackson-core
  • Jackson’s Lesson # 3: Common API operations
  • WRAP_ROOT_VALUE (root object)
  • Jackson: JsonInclude annotations
  • Jackson study # 6: Common class annotations
  • Jackson Study # 7: Common Field annotations
  • Jackson Study # 8: Notes on Common Methods
  • Springboot Integration (Configuration Files)
  • Springboot Integration (Configuration Class)

About Springboot integration Jackson

  • Learn how to use Jackson in springboot projects. Take SpringBoot-2.3.3 as an example. Jackson is the default JSON tool for Springboot, as shown in the red box below. Jackson is indirectly dependent on spring-boot-starter-web in maven configuration and can be used directly:

  • There are two common configuration methods in springboot projects:
  1. Use the Properties or YML configuration file, which is the content of this article;
  2. Using configuration classes, which is the subject of the next article;

This paper gives an overview of

Today’s actual combat content is as follows:

  1. Develop springboot application, experience springboot default support for Jackson, including Jackson annotations and ObjectMapper instance injection;
  2. Add Jackson configuration to application.yml to verify whether it takes effect.

Download the source code

  1. If you don’t want to code, you can download all the source code at GitHub, with the address and link information listed in the following table (github.com/zq2599/blog…
The name of the link note
Project home page Github.com/zq2599/blog… The project’s home page on GitHub
Git repository address (HTTPS) Github.com/zq2599/blog… The project source warehouse address, HTTPS protocol
Git repository address (SSH) [email protected]:zq2599/blog_demos.git The project source warehouse address, SSH protocol
  1. The Git project has multiple folders, and the application of this chapter is in the JacksonDemo folder, as shown in the red box below:

  1. Jacksondemo is a parent-child project. The code for this project is in the SpringBootProperties sub-project, as shown below:

Start of actual combat

  1. As part of the Jackson Learning series, this springboot project exists as a sub-project of JacksonDemo. Pop.xml is as follows. Note that parent cannot use spring-boot-starter-parent. The SpringBoot dependency is introduced via a dependencyManagement node:

      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>jacksondemo</artifactId>
        <groupId>com.bolingcavalry</groupId>
        <version>1.0 the SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>springbootproperties</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>springbootproperties</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>


    <! -- spring-boot-starter-parent -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.3. RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <! -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <! -- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code
  1. Startup classes are common:
package com.bolingcavalry.springbootproperties;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootpropertiesApplication {

    public static void main(String[] args) { SpringApplication.run(SpringbootpropertiesApplication.class, args); }}Copy the code
  1. Since swagger is used, add swagger configuration:
package com.bolingcavalry.springbootproperties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .tags(new Tag("JsonPropertySerializationController"."JsonProperty related tests"))
                .select()
                // The current package path
                .apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.springbootproperties.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    // Build the details function of the API document, note which annotation here refers to
    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                // Page title
                .title("SpringBoot integration Jackson(based on configuration files)")
                / / founder
                .contact(new Contact("Programmer Chen"."https://github.com/zq2599/blog_demos"."[email protected]"))
                / / version number
                .version("1.0")
                / / description
                .description("API description") .build(); }}Copy the code
  1. JsonProperty = JsonProperty; JsonProperty = JsonProperty; JsonProperty = JsonProperty;
package com.bolingcavalry.springbootproperties.bean;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.Date;

@apiModel (description = "JsonProperty annotation test class ")
public class Test {

    @apiModelProperty (value = "private member variable ")
    @JsonProperty(value = "json_field0", index = 1)
    private Date field0 = new Date();

    public void setField0(Date field0) {
        this.field0 = field0;
    }

    @apiModelProperty (value = "string from get method ")
    @JsonProperty(value = "json_field1", index = 0)
    public String getField1(a) {
        return "111";
    }

    @Override
    public String toString(a) {
        return "Test{" +
                "field0=" + field0 +
                '} '; }}Copy the code
  1. Serialization returns the serialization result, deserialization takes the client’s request parameters, deserialization takes the deserialization instance, and checks the deserialization result with toString(). Also use ObjectMapper instances directly from the Spring container via Autowired annotations:
package com.bolingcavalry.springbootproperties.controller;

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
    ObjectMapper mapper;

    @apiOperation (value = "test serialization ", notes =" test serialization ")
    @RequestMapping(value = "/serialization", method = RequestMethod.GET)
    public Test serialization(a) throws JsonProcessingException {

        Test test = new Test();
        logger.info(mapper.writeValueAsString(test));

        return test;
    }

    @apiOperation (value =" test deserialization ", notes=" test deserialization ")
    @RequestMapping(value = "/deserialization",method = RequestMethod.PUT)
    public String deserialization(@RequestBody Test test) {
        returntest.toString(); }}Copy the code

Validation (no configuration file)

  1. Let’s look at there is no configuration file, the default configuration of Jackson’s performance, direct run on IDEA SpringbootpropertiesApplication;
  2. The browser to http://localhost:8080/swagger-ui.html, the following figure 1 red box, json_field0 and json_field1 JsonProperty annotation, in the model of swagger, This proves that the Jackson note is in effect:

  1. Click the red box 2 in the image above to see the serialization result returned by the SpringBoot reference, as shown below:

  1. In addition, the json format in the red box above, a single line for each property, seems to have been formatted, and this is springBoot, right? Or did Swagger do it at the show? Use the browser to http://localhost:8080/jsonproperty/serialization, the results are as follows, visible springboot return is not formatted json:

  • Next let’s add jackson-related configuration information and verify whether it works.

Add the configuration file and verify

  1. Add the application.yml file to the Resources directory as follows:
spring:
  jackson:
    # date formatting
    date-format: yyyy-MM-dd HH:mm:ss
    # serialization correlation
    serialization:
      # format output
      indent_output: true
      Ignore objects that cannot be converted
      fail_on_empty_beans: true
    Deserialization is relevant
    deserialization:
      When parsing JSON, ignore non-existent attributes
      fail_on_unknown_properties: false
    How to serialize null
    defaultPropertyInclusion: NON_EMPTY
    parser:
      # Allow special and escape characters
      allow_unquoted_control_chars: true
      # Allow single quotes
      allow_single_quotes: true
Copy the code
  1. Place the mouse pointer in the red box as shown below, and then hold down the Ctlr key. IDEA will pop up a floating layer, prompting the corresponding Jackson code for this configuration, as shown below:

  1. In the image above, hold down the Ctlr key and click the red box to open the Jackson source code for this configuration, as shown below:

4. Re-run the SpringBoot application and use a browser to access:http://localhost:8080/jsonproperty/serializationThe format of jSON_field0 is yyyY-MM-DD HH: MM :ss, and the json output is formatted to show that the configuration in application.yml is valid:

5. Try deserialization again, open swagger page, action and response as shown below, notice the format of request parameters in red box 1:

  • At this point, in Springboot through the YML configuration of Jackson operation practice is completed, the next chapter, we use code in the configuration class to complete the YML configuration;

You are not alone, Xinchen original accompany all the way

  1. Java series
  2. Spring series
  3. The Docker series
  4. Kubernetes series
  5. Database + middleware series
  6. The conversation series

Welcome to pay attention to the public number: programmer Xin Chen

Wechat search “programmer Xin Chen”, I am Xin Chen, looking forward to enjoying the Java world with you…

Github.com/zq2599/blog…