org.springframework.data.redisConnectionFailureException

2023-01-10   ES  

jackson use manual

1, preface

Jackson is a pretty good JSON parser,Jackson There are many advantages: analyzing the speed of large files faster, less memory occupied during running, better performance,API Very flexible and easy to expand and customize. The core module consists of three parts:

  • jackson-coreCore package, provides related APIs based on “flow mode” analysis, including JSONPASER and JSONGENARTOR;
  • jackson-annotationsAnnotation package, provide standard annotation functions;
  • jackson-databindData binding package provides related API (ObjectMapper) based on “object binding” analysis and related API (JSONNODE) based on the “tree model” analysis;

Use Jackson divided into two cases: ordinary Maven project,SpringBoot project, the former is independent and the latter is integrated.

2, global configuration

Jackson Configuration attribute class, common configuration requirements include: global date format, global string serialization order (dictionary sorting), hump and lower line conversion.

(1) Default configuration

default configuration classJacksonProperties, the parameters that need to be followed are as follows:

parameters

meaning

default value

Remarks

date-format

Date formatting mode

None

Suggestion settingsyyyy-MM-dd HH:mm:ss

time-zone

time zone

None

Suggestion settingsGMT+8

property-naming-strategy

Attribute naming strategy

None

Suggestion settingsSNAKE_CASE

Simplified configuration

spring:

  jackson:

    date-format: ‘yyyy-MM-dd HH:mm:ss’

    time-zone: ‘GMT+8’

    mapper:

        # FormatizationJSONSort in the order of the dictionary

        sort-properties-alphabetically: true

    # The value of the front end transmits the front end from the hump to the line.

    property-naming-strategy: SNAKE_CASE

Detailed configuration

spring:

  jackson:

    # Set the attribute naming strategy,CorrespondencejacksonThe constant value inPropertyNamingStrategy,SNAKE_CASE-ReturnjsonCamel peak -style turn off the line,json bodyThe next line is passed to the back end automatic turning the hump

    property-naming-strategy: SNAKE_CASE

    # global settings

Format of@JsonFormatpattern

    date-format: yyyy-MM-dd HH:mm:ss

    # Local time zone

    locale: zh

    # Set the global time zone

    time-zone: GMT+8

    # Commonly used, global settingspojoor being@JsonIncludeAnnotation of the attributes of the attribute

    default-property-inclusion: NON_NULL #The attributes that are not empty will be serialized,specific attributes can be seenJsonInclude.Include

    # Conventional default,enumeration category

The enumeration attribute inSerializationFeatureiskey, the value isbooleanSettingsjacksonserialization characteristics,specifickeyPlease seeSerializationFeaturesource code

    serialization:

      WRITE_DATES_AS_TIMESTAMPS: true # Returnjava.util.dateConverted intotimestamp

      FAIL_ON_EMPTY_BEANS: true # Objects report an error when empty, defaulttrue

    # enumeration category

The enumeration attribute inDeserializationFeatureiskey, the value isbooleanSettingsjacksonReverse sequentialization characteristics,specifickeyPlease seeDeserializationFeaturesource code

    deserialization:

      # Commonly used,jsonpojoWhether it fails when there is no attribute to report an error,defaulttrue

      FAIL_ON_UNKNOWN_PROPERTIES: false

    # enumeration category

The enumeration attribute inMapperFeatureiskey, the value isbooleanSettingsjackson ObjectMapperFeatures

    # ObjectMapperjacksonResponsiblejsonread and write,jsonandpojo‘s mutual turn,json tree,Please see the specific featuresMapperFeature,Conventional default

    mapper:

      # UsegetterreplacementsetterDetective attributes, such as in the classgetName()but not containingnameattribute and attributesetName(), transmittedvo jsonFormat template still containsnameattribute

      USE_GETTERS_AS_SETTERS: true #defaultfalse

    # enumeration category

The enumeration attribute in theJsonParser.Featureenumeration category iskey, the value isbooleanSettingsjackson JsonParserFeatures

    # JsonParserjacksonResponsiblejsonReading of content,Please seeJsonParser.Feature, generally no need to set the default

    parser:

      ALLOW_SINGLE_QUOTES: true # Whether the single quotation number is allowed,defaultfalse

    # enumeration categoryJsonGenerator.Featureenumeration category enumeration attributes arekey, the value isbooleanSettingsjackson JsonGeneratorFeatures, generally no need to set the default

    # JsonGeneratorjacksonResponsible for writingjsonContent,12 12 Please seeJsonGenerator.Feature

3. Personalized configuration

1. Properties dictionary sorting

If you do not add any configuration of the order of attributes, the default order is formatted in the physical class by default; JSON The field is sorted in the sequence of the dictionary, and the formatted field is sorted in the sequence of the dictionary. If you have special needs, use annotations@JsonPropertyOrder Custom sorting field sort order.

@JsonPropertyOrder({“resName”, “checkStatus”,”buildExportVo”})

public class FirstExportVo {

    private String resName;

    private Integer checkStatus;

    private List<BuildExportVo> buildExportVo = new ArrayList<>();

}

When the field is easy to change, such as the rename operation, the more elegant solution is as follows:

public class FirstExportVo {

    @JsonProperty(index = 1)

    private String resName;

    @JsonProperty(index = 2)

    private Integer checkStatus;

    @JsonProperty(index = 3)

    private List<BuildExportVo> buildExportVo = new ArrayList<>();

}

2, date format

If in the global configuration time date formatyyyy-MM-dd HH:mm:ss, need in special occasions

The date ofyyyy-MM-ddformat can be achieved through the following annotations. Adding annotations on the field are higher than the global configuration.

@JsonFormat(pattern = DateTimeFormatter.ISO_DATE)

private Date birthDay;

3, the hump and the lower lines turn each other

The value of the front end transmits the front end is turned down from the hump. When the front -end transmits parameters to the back end, the parameters represented by the lower line are identified in the request body. The parameters expressed by the hump rules are invalidated after the strokes are effective.

MyBatis can also be configured with the line and the hump to each other,Jackson 4 MVC level implementation,MyBatis 6 ORM level implementation.

spring:

  jackson:

    # The value of the front end transmits the front end is turned down from the hump, and the parameters transmitted to the back end to the back -end are transferred from the bottom line to the hump.

    property-naming-strategy: SNAKE_CASE

4. Use experience

Introduction to dependencies

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.12.2</version>

</dependency>

jackson-databind dependence on jackson-core and jackson-annotations, by maven automatic management related dependencies, users do not need to add additional addition.

(1) Basic use

The object here refers to simple POJOJSON field and Java Object attributes do not involve inheritance relationships.

JSON and objects to each other in nature belong to serialization and deepertine. Compared with general binary serialization, here is

The serialization of JSON string.

1. JSON Transfer Object

User[] users = objectMapper.readValue(new File(“/tmp/111.json”), User[].class);

// JSONstring convert to object (replacement of placeholders)

objectMapper.readValue(“JSONstring“, User[].class);

// byte array converted into objects (replacement of placeholders)

objectMapper.readValue(new byte[16], User[].class);

2, object to JSON

Jackson writeValueseries method will Java Object serialization to JSON, support stored in different formats.

ObjectMapper mapper = new ObjectMapper();

// Converted toJSONand store it as a file

mapper.writeValue(new File(“/tmp/111.json”),list);

// Converted toJSONstring

String content = mapper.writeValueAsString(list);

Convert the object into byte array.

// Converted into byte array

byte[] bytes = mapper.writeValueAsBytes(list);

(2) New date type

New Date Common ClassLocalDateLocalDateTimetwo types,Jackson In the process of handling the new date, it is not smooth. Compared with other basic types, the following two types of problems need to be solved: formatting and serialization.

Features

Data flow

Serializable

Format

one -way

Memory object —> JSON string

No need to implement

serialization

two -way

Memory object <—> Other storage media

Need to achieve

1、LocalDate

@Bean

public Jackson2ObjectMapperBuilderCustomizer localDateCustomizer() {

    return builder -> builder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_DATE));

}

2、LocalDateTime

I used herehutool-coreBagsDatePatternClass.

@Bean

public Jackson2ObjectMapperBuilderCustomizer localDateTimeCustomizer() {

    return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));

}

If the global configuration is not effective, configure it directly in the physical class

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”)

@JsonDeserialize(using = LocalDateTimeDeserializer.class)

@JsonSerialize(using = LocalDateTimeSerializer.class)

(3) Advanced use

The

1、Long

Longtype field needs to be serialized, considering the front end JS cannot be accommodated

The Long type data needs to be converted into a string. Similarly, the front end also uses a string to transmit data in the back end.

@Bean

public Jackson2ObjectMapperBuilderCustomizer longCustomizer() {

    return builder -> builder.serializerByType(Long.class, ToStringSerializer.instance);

}

2. Time stamp formatting

In the process of processing the globalization business, the time format of the database storage is

The timestamp of the 13 bit (unit: millisecond), the following ways can quickly achieve the date formatting (shielding the air pointer abnormalities).

@JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN)

public LocalDateTime getCreateTime() {

    Function<Long, LocalDateTime> mapper = e -> LocalDateTime.ofInstant(Instant.ofEpochMilli(e), ZoneId.systemDefault());

    return Optional.ofNullable(this.createTime).map(mapper).orElse(null);

}

Solving the idea is to beTime stampConverted intoLocalDateTimeinstance, and then use the default Jackson Format formatting date output.

3, empty value processing

For the empty value, serialization becomes JSON string is not significant, so it can be passed@JsonInclude(JsonInclude.Include.NON_NULL)Category annotation filtering vacancy field.

If you have helpful, I hope to give it three consecutive companies. Your encouragement is my motivation to move forward. thanks
Follow me: Private message Get Java advanced architecture data, big factory interview questions, video

source

Related Posts

UVA -10001 Garden of Eden

tyvj P1062 merged fool

R language cluster analysis-KMEANS cluster analysis actual combat

MATLAB random number generation method

org.springframework.data.redisConnectionFailureException

Random Posts

wizNet News-IMCU W7200, Cortex M3 based on ARM 32bit!

1 1 1 1 1 1 (Basic Article) -Tezon chapter, computer Introduction (zero .5)

Simple SetContentOffset, SetContentsize, and several simple animation use J

SQL Server Database Create J

IOS welcome interface Launch Screen dynamically loaded ads