Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

At the end of the Eastern Han Dynasty, The Three Kingdoms were divided, the flames of war were endless, the children were left and right, who would cook the wine, the intriguities were The Three Kingdoms, couldn’t tell right and wrong, after thousands of years of confusion, everything began again.

Hello, I’m Jackson.

The stars are shining and the wind is soft. With the sky as the curtain, with the ground as the mat, I was sitting on the ground, enjoying the cool summer night, listening to a pool of frogs calling a worm, looking at the starry night sky, suddenly, a strong wind, thunder and lightning, a lightning hit me, my eyes black, I fainted, and then found myself in the Eastern Han Dynasty Java year

In the eastern Han Dynasty, Java serialization tools became three factions, namely, Jackson of Cao Wei, Gson of Shu Han, and FastJson of Dongwu

The cao Jackson

Jackson has been called the “Java JSON library” or “Java’s best JSON parser.” Or “JSON for Java” for short.

Github:github.com/FasterXML/j…

Before the Battle of Red Cliff, I Jackson mercenaries of millions, generals of thousands, how arrogant, sun and moon travel, if out of it, the stars are brilliant, if out of it. After this it is more broken Jingzhou, lower Jiangling, downstream and eastern also, 舳舻 Trinidad, jingflags cover the empty, wine Linjiang, horizontal lance fushi (wine singing, geometry of life), solid male also

Shu han Gson

Gson is a Java library that can be used to transform Java objects into their JSON representation. It can also be used to convert JSON strings into equivalent Java objects. Gson can work with any Java object, including pre-existing objects for which you have no source code. Github website: github.com/google/gson

Just like Gson did

Mr. Zhang:

Zhao is a minor man in the east of the river, long heard Mr. High lying long, since the pipe, music. There is something in this language

Gson:

Gson’s life is a lot smaller than that

Mr. Zhang:

I heard that Mr. Liu Yuzhou three gu in the grass cottage, Mr. Xingde, thought that ‘like a fish in water’, thought to sweep Jingxiang. Once belongs to cao Cao today, is not examined what main idea?

Gson:

I think it’s easy to take the land of Han shang. My master Liu Yuzhou practice benevolence and justice, can not bear to seize the foundation of the same clan, so he resigns. Liu Cong Ruzi, listening to the sycophants, secretly surrendered, resulting in the rampant Cao Cao. Now my Lord camp jiangxia, do not have a good map, not easy to know also

Mr. Zhang:

If this is the master’s words and deeds are also contrary. Mr. Huan Gong, the prime minister of Guan Zhong, overlords, a kuang the world; Yue Yi supported the weak Yan and took over seventy cities under his command: these two men were truly talented in helping the world. Mr. Grass in the hut, but proud wind and moon smile, knee sitting. Now engaged in Liuyuzhou, when life xingli, exterminate bandits. And Liu Yuzhou did not get Mr. Before, and the world, the city; Mr. Jin de, people look up to. Although three feet tong Meng, also known as the Tiger wing, will see the Han room revival, cao’s is out. Old court-officials and hermits wiped their eyes, thinking that they were brushing the clouds of the sky, admiring the rays of the sun and the moon, living in the midst of fire and water, and taking care of the whole world over the front feast. Mr. He returned to Yuzhou, Cao soldiers out, abandoned armor and guard, and flee; Liu Biao can not be reported to the security of the subaltern, the next can not auxiliary soliton and according to the territory; He abandoned Xinye, went to Fancheng, was defeated in The sun, and ran towards the mouth of summer with no place of refuge: after yuzhou had won the master, it was not as good as it had been at the beginning. Guan Zhong and Yue Yi, is this the case? Foolish words, fortunately do not be offended!

Gson:

Peng fei thousands of miles, its ambition or birds can know zai? For example, people infected with chronic diseases, when the first with porridge to drink, and medicine to take; To be reconciled to the heart, the body gradually, and then with meat to repair it, violent medicine to cure it: then the root of the disease is gone, the whole life. If you do not wait for the pulse of qi and slow, then with strong medicine thick taste, desire for security, honesty difficult. To the Japanese defeat Lord Liu Yuzhou Yu Runa, a sojourner biao3, soldier dissatisfaction thousands, will check guan, zhang, zhaoyun: this as an attempt 尫 very when also won, and the new wild plant lolipop 】 people’s scarce, fresh thin grain, and state but of short duration to shelter, is really will be half in this? However, the burning of bo Wang and the use of water in the Baihe river made Xiahou Dun and Cao Ren terrified: the stealing of Guan Zhong and Yue Yi’s troops may not go beyond this. As for Liu Cong down cao, Yu Zhou out of the fact THAT I do not know; And can not bear to take the inheritance of the same clan by chaos, this is really generous and righteous. The defeat of Dangyang, Yuzhou saw hundreds of thousands of people go to righteousness, old and young together, can not bear to abandon it, day line ten miles, do not think of forging ahead jiangling, gan and with defeat, this is also great benevolence and righteousness also. Being outnumbered, it is not unusual to win or lose. In the past, Gao Huang was defeated by Xiang Yu, and Gaixia succeeded in the war. Is this not the good plan of Han Xin? Husband letter long matter gao Huang, never tired of victory. There is a mastermind to cover the state and the security of the country. Those who do not boast boast and deceive others: no one can sit and talk; Nothing can be done at the last moment. — Smile for the world!

Dongwu FastJson

Fastjson is Alibaba’s open source JSON parsing library, which can parse JSON-formatted strings and support serialization of Java beans to JSON strings, as well as deserialization from JSON strings to Javabeans.

Github website: github.com/alibaba/fas…

The great river goes east, the waves are all gone, the gallant men of past ages. So base west, humanity is: three Kingdoms FastJson Red Cliff. The rocks Pierce the sky, the waves roll up thousands of piles of snow, and the feathers will stretch out their necks in conversation and laughter.

In the post-Red Cliff era, Jackson Gson FastJson is in a three-way battle. Let’s take a look at the pros and cons of each

Jackson, fastjson Gson

  • Jackson: Reflection + reflection cache, good stream support, efficient memory management
  • fastjson
    • JVM VMS: Generate parser bytecode using ASM libraries. The number of fields supported cannot exceed 200.
    • Android VM: Reflection mode
  • Gson: Reflection + reflection cache, partial stream support, poor memory performance (GC issues)

ASM

  • ASM is a Java bytecode manipulation framework. It can be used to dynamically generate classes or enhance the functionality of existing classes. ASM can either generate binary class files directly or dynamically change the behavior of classes before they are loaded into the Java virtual machine.
  • ASM can modify existing classes to generate the required code directly. The enhanced code is hardcoded inside the newly generated class files, with no performance penalty due to reflection.
  • ASM can be used to implement AOP.

Reflection performance

  • Reflection performance differs by two orders of magnitude (a hundred times) from object direct access performance.
  • Reflection consumes a large part of its performance in traversing the Field.
  • Reflection caching can improve performance by an order of magnitude.

Jackson characteristics

Here are some of Jackson’s features and uses

  • Jackson has a flexible API that can be easily extended and customized, and in many cases the required modules are already provided. Data types defined in Guava, such as the Kotlin Immutable type, and new date-time types introduced in Java8 and Optional are already supported by modules.
  • Some null handlers need to print NULL and want to preserve the field. Some need not output, output results in the exclusion of null values.
  • Empty string processing may require null, no, or “”
  • Bool handlers either print 0/1 or true/false
  • The custom object handles various conversions between DateTime, Long and Timestamp
  • Some missing fields need to be reported, some need to ignore.
  • Field mapping You call her “chick”, I call her “little sister”.
  • XML support, YAML support…

Jackson simple to use

  • Rely on
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> The < version > 2.11.1 < / version > < / dependency >Copy the code

The thing to note here is that most people think that I need to refer to Jackson with a lot of dependencies like his core and his annotations and so on, but databind already includes those, so we can just refer to Databind

  • The simplest example

ExtendableBean

package com.six.finger.leetcode.jackson; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; @JsonPropertyOrder({ "age", "name" }) @JsonRootName("user") class ExtendableBean { private String name; private String age; @JsonFormat( shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") private Date date; @JsonAnySetter private Map<String, String> properties = new HashMap<>(); @JsonAnyGetter public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; }}Copy the code

TestJsonAny

package com.six.finger.leetcode.jackson; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class TestJsonAny { public static void main(String[] args) { String json = "{"name":"My bean","attr2":"val2","attr1":"val1","age":"18","date":"20-12-2014 02:30:00"}"; ObjectMapper objectMapper = new ObjectMapper(); try { ExtendableBean bean = objectMapper .readerFor(ExtendableBean.class) .readValue(json); System.out.println(bean); System.out.println(objectMapper.writeValueAsString(bean)); } catch (IOException e) { e.printStackTrace(); }}}Copy the code

Some of Jackson’s common configurations and annotations

@JsonAnyGetter

The @JsonanyGetter annotation allows the use of a flexible map field as a standard property.

For example, the ExtendableBean entity has a name attribute and a set of extendable attributes in the form of key/value pairs:

When we serialize an instance of this entity, we treat all the key values in the Map as standard, common attributes:

@JsonPropertyOrder

We can specify the sequence of serialized properties using the @JsonPropertyOrder annotation.

Let’s set a custom order for the properties of MyBean entities:

Here is the serialization output:

@JsonRootName

The @jsonRootName annotation is the name of the root directory used in the specified wrapper if the package is enabled.

Wrapping means that instead of serializing the User to the following:

It will be packaged like this:

@JsonSerialize

@jsonSerialize represents a custom serializer to use when marshalling entities.

Let’s look at a simple example. We’ll serialize the eventDate property via CustomDateSerializer using @jsonSerialize:

This is a simple custom Jackson serializer:

@JsonAlias

The @JsonAlias defines the deserialization process as one or more alternative names for attributes.

Let’s look at a simple example of how this annotation works:

Here we have a POJO, and we want to deserialize JSON with fName, F_name, and firstName values into the POJO’s firstName variable.

Here are the tests to make sure this annotation works as expected:

The Jackson-based JSON utility class encapsulates JsonUtils

import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.io.IOException; import java.text.SimpleDateFormat; import lombok.extern.slf4j.Slf4j; @slf4j public class JsonUtils {private static ObjectMapper om = new ObjectMapper(); Static {/ / object list all all of the fields, or other options, you can ignore null etc. Om setSerializationInclusion (Include. ALWAYS); Om.setdateformat (new SimpleDateFormat(" YYYY-MM-DD HH: MM :ss")); / / ignore empty Bean json error om. The configure (SerializationFeature FAIL_ON_EMPTY_BEANS, false); / / ignore unknown attribute, prevent the json string, exist in the Java object does not exist in the corresponding properties of errors om. The configure (DeserializationFeature FAIL_ON_UNKNOWN_PROPERTIES, false); Om.registermodule (new JavaTimeModule()); } public static <T> String toJson(T obj) {String json = null; if (obj ! = null) { try { json = om.writeValueAsString(obj); } catch (JsonProcessingException e) { log.warn(e.getMessage(), e); throw new IllegalArgumentException(e.getMessage()); } } return json; } /** * json String => object ** @param JSON source JSON String * @param clazz object class * @param <T> generic */ public static <T> T parse(String) json, Class<T> clazz) { return parse(json, clazz, null); } /** * JSON String => object ** @param JSON source JSON String * @param type Object type * @param <T> generic */ public static <T> T parse(String) json, TypeReference type) { return parse(json, null, type); } /** * json => object handling method * <br> * clazz and type must be null, the other is not null * <br> * This method is not external, Access permission: private * * @param JSON source JSON string * @param clazz object class * @param Type Object type * @param <T> generic */ private static <T> T parse(String json, Class<T> clazz, TypeReference type) { T obj = null; if (! StringUtils.isEmpty(json)) { try { if (clazz ! = null) { obj = om.readValue(json, clazz); } else { obj = om.readValue(json, type); } } catch (IOException e) { log.warn(e.getMessage(), e); throw new IllegalArgumentException(e.getMessage()); } } return obj; }}Copy the code

The end of the

In fact, I used to use Fastjson before, but later fastjson had too many bugs, so I always had to upgrade, so I changed to Jackson. I think it’s better to use a tool for a project, and Jackson also supports XML serialization. And it’s a tool for SpringMvc, so it’s not a fan. Those who have been developed recently just revisited The Three Kingdoms, lamenting the charm of the romance of The Three Kingdoms and sharing it with you. I am small 66, three days fishing, two days drying nets.