The standard JSON library for Java (or the JVM platform), otherwise known as “Java’s best JSON parser.”

Jackson provides a suite of data processing tools for the Java (and JVM platform), including a flagship stream JSON parser/generator library, a matching data binding library (POJOs between JSON), and additional data format modules. Processing data encoded by Avro, BSON, CBOR, CSV, Smile, (Java) Properties, Protobuf, XML or YAML; There are even a number of data format modules to support data types of widely used data types, such as Guava, Joda, PCollections, and so on.

The actual core components are located under their own project – including two core packages: Jackson-core and Jackson-Databind.

The Jackson-core project contains the abstract core stream parser and generator used by the Jackson data processor, as well as a default implementation of the parser and generator for handling JSON formats. Jackson-databind contains common data binding capabilities and a tree model for the Jackson data processor. It is built on the StreamingAPI (stream parser, generator) package and configured using Jackson annotations.

1 Streaming API Core Streaming API

Streaming apis are a relatively low-level set of apis that are fast, but particularly cumbersome to use. It has two core classes: JsonGenerator, which generates JSON, and JsonParser, which reads JSON content. Usage typically starts by creating reusable (and thread-safe) JsonFactory instances:

JsonFactory factory = new JsonFactory(); // Configuration (if necessary) : factory.enable(jsonParser.feature.allow_comments); // Alternatively, you can easily ObjectMapper (available from the jackson-Databind package). If so, you can do the following: JsonFactory Factory = objectMapper.getFactory();Copy the code

Official usage example: Reading and Writing Event Streams

JsonFactory f = mapper.getFactory(); JsonFactory = new JsonFactory(); JsonFile = new File("test.json"); JsonGenerator g = f.createGenerator(jsonFile); // write JSON: {"message" : "Hello world!" }
g.writeStartObject();
g.writeStringField("message"."Hello world!");
g.writeEndObject();
g.close();

// 然后读取
JsonParser p = f.createParser(jsonFile);

JsonToken t = p.nextToken(); 
t = p.nextToken(); 
if((t ! = JsonToken.FIELD_NAME) || !"message".equals(p.getCurrentName())) {
   // handle error
}
t = p.nextToken();
if(t ! = JsonToken.VALUE_STRING) { // similarly } String msg = p.getText(); System.out.printf("My message to you is: %s! \n", msg);
p.close();
Copy the code

2 Data Binding Data Binding

The Jackson-Databind package relies on the Jackson-core and Jackson-Annotations package, but dependencies are automatically included when using a build tool like Maven or Gradle. Basic use:

/ / create a com. Fasterxml. Jackson. Databind. ObjectMapper for all instances of data binding, ObjectMapper is thread-safe, should try to reuse. ObjectMapper mapper = new ObjectMapper(); Grade Grade = mapper.readValue(jsonStr, Grade. Class); // Jackson serializes properties based on Javabeans, with GETTER methods, Map<String, ResultValue> Results = mapper.readValue(jsonSource, new TypeReference<Map<String, ResultValue>>() { } ); / / object serial number into a json String String gradeStr = mapper. WriteValueAsString (grade); Byte [] jsonBytes = mapper.writevalueasBytes (grade); Mapper. writeValue(new File("result.json"), grade);
Copy the code

3 Tree Model

Creating a corresponding class for JSON is inconvenient when an API is called and the returned JSON data needs to be parsed for information. It is convenient to parse json using the Tree Model

JsonNode root = mapper.readTree(rerenjson);
JsonNode user = root.get("user");
root.with("other").put("type"."student");
int id = user.get("id").asInt();
String name = user.get("name").asText();
JsonNode avators = user.get("avatar");
if (avators.isArray()) {
    for(Iterator it = avators.getElements(); it.hasNext(); ) { JsonNode avator = it.next();if ("tiny".equals(avator.get("type").asText())) {
            String ava = avator.get("url").asText();
            break; }}}Copy the code

4 Type Conversion

A useful (but not well known) feature of Jackson is its ability to do arbitrary POJO-to-POJO transformations. The general approach is to first write the POJO as JSON, and then bind the JSON to another POJO. The Jackson implementation skips the actual JSON generation and uses a more efficient intermediate implementation.

ResultType result = mapper.convertValue(ResultType result = mapper.convertValue(sourceObject, ResultType.class); // List<Integer> int[] List<Integer>sourceList = ... ; int[] ints = mapper.convertValue(sourceList, int[].class); / / POJO Map! Map<String,Object> propertyMap = mapper.convertValue(pojoValue, Map.class); POJO = mapper.convertValue(propertyMap, pojotype.class); // Decode Base64! (The default byte [] indicates a base64 encoded String.) String Base64 ="TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz";
byte[] binary = mapper.convertValue(base64, byte[].class);
Copy the code

5 Common Comments and Configurations

1. Common annotations: @jsonignore This annotation is used on properties to ignore them during JSON operations. @jsonFormat This annotation is used on attributes to convert the Date type directly to the desired format, such as @jsonFormat (pattern = “YYYY-MM-DD HH-MM-SS”). @jsonProperty This annotation is used on a property to serialize the name of the property to another name, such as the trueName property to name, @jsonProperty (” name “). You can also add the @jsonIgnoreProperties ({“a”, “b”}) annotation directly to the class, skipping the A and B attributes. The @jsonCreator constructor can be public or private. Jackson does not need to define a “default constructor” (a constructor that takes no arguments).

2. Some useful configurations for Mapper :(see jackson-databind link above for other configurations)

/ / (empty object whether an exception is thrown) mapper. Disable (SerializationFeature. FAIL_ON_EMPTY_BEANS); / / (dates to the timestamp) mapper. Disable (SerializationFeature. WRITE_DATES_AS_TIMESTAMPS); Mapper. configure(jsonparser.feature. ALLOW_UNQUOTED_FIELD_NAMES,true); // (single quotes) mapper.configure(jsonparser.feature. ALLOW_SINGLE_QUOTES,true);
Copy the code

6 Use Jackson in SpringBoot

The SpringMVC built-in JSON parser is Jackson, and the default Jackson is best for SpringBoot stack development.

spring:
    jackson:
      SNAKE_CASE- Return JSON camel underline, json body underline is automatically camel underline when passed to the back end
      property-naming-strategy: SNAKE_CASE
      # set @jsonformat pattern
      date-format: yyyy-MM-dd HH:mm:ss
      # Local time zone
      locale: zh
      Set the global time zone
      time-zone: GMT+8
      Set the serialization of poJOs or attributes annotated by @jsoninclude globally
      default-property-inclusion: NON_NULL {jsoninclude.include}} {jsoninclude.include
      By default, the enumeration property in SerializationFeature is key, and the value is Boolean
      serialization:
        WRITE_DATES_AS_TIMESTAMPS: true # return java.util.date to timestamp
        FAIL_ON_EMPTY_BEANS: true # Whether to report an error if the object is empty. Default is true
      # enumeration class DeserializationFeature in the enumeration attribute is key, value is Boolean set Jackson deseriationfeature, specific key see DeserializationFeature source code
      deserialization:
        If poJO does not exist in json, the error will be reported. Default is true
        FAIL_ON_UNKNOWN_PROPERTIES: false
      Set the Jackson ObjectMapper feature to key and Boolean
      ObjectMapper is used to read/write JSON, interwrite JSON with POJOs, interwrite JSON tree, etc
      mapper:
        # Use getters instead of setters to detect properties. For example, if the class contains getName() but does not contain the name property and setName(), the vo JSON format template transmitted still contains the name property
        USE_GETTERS_AS_SETTERS: true # the default false
      JsonParser Feature Set the Jackson JsonParser Feature to key and Boolean
      # JsonParser is used to read JSON content in Jackson. See JsonParser for details
      parser:
        ALLOW_SINGLE_QUOTES: true # Whether single quotes are allowed. Default is false
      JsonGenerator Feature set the Jackson JsonGenerator Feature to key and Boolean
      # JsonGenerator is responsible for writing JSON content in Jackson, see JsonGenerator
Copy the code

Either the default configuration (JacksonAutoConfiguration for configuration files) or the user-defined Java code configuration is required.


conclusion

Jackson Jackson-core Jackson-databind is one of the most commonly used data binding services in the world. It’s a great way to configure it. Tree models and type conversions also make it easier to use the streaming API. I hope you found this article helpful. Welcome to study together, please correct the mistakes.