Jackson API Guide

Jackson overview and dependencies

  1. There are dozens of third-party libraries on the market for parsing Json in Java, the best of which are Google's Gson , Alibaba's Fastjson and this article's jackson.

  2. Before we learn a technology, we first need to understand the advantages and disadvantages of this technology, as well as its comparison with the same technology. fastjson is so fast, why are foreigners still keen on jackson?

  3. Using Jackson to import jackson-databind, jackson-annotations, and jackson-core3 main modules basically satisfies the development, which jackson-databindinternally depends on jackson-annotationsand jackson-core, so when Maven is applied, as long as one is imported , the and dependencies jackson-databindare also imported .jackson-annotationsjackson-core

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.0</version>
    </dependency>
    
    

Jackson usage feed

1. By default, when ObjectMapper serializes objects, all fields of the entity are serialized one by one, regardless of whether these fields have values ​​or are null.

2. If a field of the entity does not provide a getter method, the field will not be serialized.

3. The Spring Boot Web component uses Jackson to serialize and deserialize objects by default, that is, the parameters passed in on the page will be automatically deserialized into background objects, and the objects passed from the background to the front end will also be serialized and output. Therefore, it should be noted that the object returned to the page cannot be serialized by Json library other than Jackson by default. For example, if a Gson JsonObject is returned to the front end, an error will be reported, because obviously Jackson will fail when serializing.

4. Jackson provides three different methods to manipulate JSON:

1)流式API - 使用 Stream(流) 的方式对 Json 的每一个组成部分进行最细粒度的控制,JsonParser 读取数据,JsonGenerator 写入数据。

2)树模型 - 将 JSON 文件在内存里以树的形式表示,通过 JsonNode 处理单个Json节点,类似于 XML 的 DOM 解析器。(常用)

3)databind 模块 - ObjectMapper 读/写 JSON 是 POJO 序列化与反序列化 Json 最方便的方式。(常用)

ObjectMapper serialized objects

1. ObjectMapper is mainly used to serialize and deserialize Java objects (such as POJO, List, Set, Map, etc.).

2. In addition to converting between Json strings and Java objects, ObjectMapper can also convert Json strings and JsonNode.

Conversion of Java objects to Json strings

method illustrate
String writeValueAsString(Object value) 1. It is used to serialize any Java object (such as POJO, List, Set, Map, etc.) into a json string. If the value of an attribute in the object is null, it will also be serialized to null by default; 2. If the value is null, the serialized result will also return
null
byte[] writeValueAsBytes(Object value) Serialize java object to byte array
writeValue(File resultFile, Object value) Serialize the java object and output it to the specified file
writeValue(OutputStream out, Object value) Serialize and output the java object to the specified byte output stream
writeValue(Writer w, Object value) Serialize and output the java object to the specified character output stream
T readValue(String content, Class valueType) 1. Deserialize from a given JSON string to a Java object;
2. If the content is empty or null, an error will be reported;
3. valueType indicates the result object of deserialization, which can be any java object, such as POJO, List, Set, Map, etc.
T readValue(byte[] src, Class valueType) Deserialize byte array of json content to java object
T readValue(File src, Class valueType) Deserialize a file of local json content into a java object
T readValue(InputStream src, Class valueType) Deserializes a byte input stream of json content to a java object
T readValue(Reader src, Class valueType) Deserializes a character input stream of json content into a java object
T readValue(URL src, Class valueType) Deserialize json content into java object through network url address

Deserialize Json string content to Json node object

method illustrate
JsonNode readTree(String content) Deserialize the JSON string into a JsonNode object, that is, a json node object
JsonNode readTree(URL source) Deserialize the json file on the network into a json node object
JsonNode readTree(InputStream in) Deserialize the json file input stream into a json node object
JsonNode readTree(byte[] content) Deserialize json byte array to json node object
JsonNode readTree(File file) Deserialize the local json file into a json node object

Conversion of Java objects and Json node objects

method illustrate
T convertValue(Object fromValue, Class toValueType) Serialize Java objects (such as POJO, List, Map, Set, etc.) into Json node objects.
T treeToValue(TreeNode n, Class valueType) Convert json tree node object to Java object (such as POJO, List, Set, Map, etc.)
TreeNode tree node is the root interface of the entire json node object model.

Api demo source code: https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/jackson/ObjectMapperTest.java

JsonNode tree model Json node

1. JsonNode represents a json node. The root interface of the entire node model is TreeNode. The json node is mainly used to manually construct json objects.

2. JsonNode has implementation classes of various data types, among which the most commonly used ones are ObjectNode and ArrayNode, the former represents a json object, and the latter represents an array of json objects.

3. The json node object can be created through JsonNodeFactory, such as JsonNodeFactory.instance.objectNode();

JsonNode json node common method

method illustrate
JsonNode get(String fieldName) Used to access the value of the specified field of an object node, or null if this node is not an object, or does not have a value for the specified field name, or does not have a field with such a name.
JsonNode get(int index) Access the value at the specified index position of the array node, for other nodes, always return null.
Returns null if the index is less than 0, or equal to or greater than the node size, no exception is raised for any index.
boolean isArray() Determine whether this node is an {@link ArrayNode} array node
boolean isObject() Returns true if this node is an object node, false otherwise
int size() Get the size of the json node, such as how many key-value pairs are in the json object, or how many elements are in the json array.
ObjectNode deepCopy() json node object deep copy, equivalent to cloning
Iterator fieldNames() Get all keys in the json object
Iterator elements() If the node is a JSON array or object node, access all value nodes of this node. For object nodes, field names (keys) are not included, and only values ​​are included. For other types of nodes, an empty iterator is returned.
boolean has(int index) Checks if this node is an array node and contains the specified index.
boolean has(String fieldName) Checks if this node is a JSON object node and contains the value of the specified property.

The value of the Json attribute is converted to a java data type

method illustrate
int asInt()
int asInt(int defaultValue)
asInt(): Attempt to convert the value of this node to int type, Boolean value false is converted to 0, true is converted to 1. If it cannot be converted to int (for example, the value is a structured type such as an object or an array), the default value 0 will be returned and no exception will be thrown.
asInt(int defaultValue): set the default value
boolean asBoolean()
boolean asBoolean(boolean defaultValue)
asBoolean(): Attempts to convert the value of this node to a Java Boolean value, integers other than 0 are mapped to true, 0 is mapped to false, and the strings "true" and "false" are mapped to the corresponding values. If it cannot be converted to a boolean value (including structured types such as objects and arrays), the default value false is returned and no exception is raised.
asBoolean(boolean defaultValue): You can set the default value yourself.
String asText()
String asText(String defaultValue)
如果节点是值节点(isValueNode 返回 true),则返回容器值的有效字符串表示形式,否则返回空字符串。
long asLong()
long asLong(long defaultValue)
与 asInt 同理
double asDouble()
double asDouble(double defaultValue)
尝试将此节点的值转换为 double,布尔值转换为0.0(false)和1.0(true),字符串使用默认的Java 语言浮点数解析规则进行解析。
如果表示不能转换为 double(包括对象和数组等结构化类型),则返回默认值 0.0,不会引发异常。
BigInteger bigIntegerValue() 返回此节点的整数值(BigDecimal),当且仅当此节点为数字时(isNumber}返回true)。
对于其他类型,返回 BigInteger.ZERO。
boolean booleanValue() 用于访问 JSON 布尔值(值文本“true”和“false”)的方法,对于其他类型,始终返回false
BigDecimal decimalValue() 返回此节点的浮点值 BigDecimal, 当且仅当此节点为数字时(isNumber 返回true),对于其他类型,返回 BigDecimal.ZERO
double doubleValue() 返回此节点的64位浮点(双精度)值,当且仅当此节点为数字时(isNumber返回true),对于其他类型,返回0.0。
float floatValue() 返回此节点的32位浮点值,当且仅当此节点为数字时(isNumber返回true),对于其他类型,返回0.0。
int intValue()
long longValue()
Number numberValue()
short shortValue()
String textValue()
返回此节点的 int、long、Number、short、String 值。

ObjectNode 对象节点常用方法

方法 说明
ObjectNode put(String fieldName, String v)
ObjectNode put(String fieldName, int v)
1、将字段的值设置为指定的值,如果字段已经存在,则更新值,value 可以为 null.
2、其它 8 种基本数据类型以及 String、BigDecimal、BigInteger 都可以 put,但是没有 Date 类型
3、Date 日期类型只能通过 Long 长整型设置
ArrayNode putArray(String fieldName) 构造新的 ArrayNode 子节点,并将其作为此 ObjectNode 的字段添加。
ObjectNode putNull(String fieldName) 为指定字段添加 null 值
ObjectNode putObject(String fieldName) 构造新的 ObjectNode 字节的,并将其作为此 ObjectNode 的字段添加。

替换与删除元素

方法 说明
JsonNode replace(String fieldName, JsonNode value) 将特定属性的值替换为传递的值,字段存在时更新,不存在时新增
JsonNode set(String fieldName, JsonNode value) 设置指定属性的值为 json 节点对象,字段存在时更新,不存在时新增,类似 replace 方法
JsonNode setAll(Map<String,? extends JsonNode> properties) 同时设置多个 json 节点
JsonNode setAll(ObjectNode other) 添加给定对象(other)的所有属性,重写这些属性的任何现有值
ArrayNode withArray(String propertyName) 将 json 节点转为 json 数组对象
ObjectNode with(String propertyName) 将 json 节点转为 ObjectNode 对象
JsonNode remove(String fieldName) 删除指定的 key,返回被删除的节点
ObjectNode remove(Collection fieldNames) 同时删除多个字段
ObjectNode removeAll() 删除所有字段属性
JsonNode without(String fieldName) 删除指定的 key,底层也是 remove
ObjectNode without(Collection fieldNames) 同时删除多个字段,底层也是 removeAll

ArrayNode 数组节点常用方法

方法 说明
ArrayNode add(String v) 将指定的字符串值添加到此 json 数组的末尾,其它数据类型也是同理。
除了可以添加 String 类型,还有 Java 的 8 种基本数据类型,以及 BigDecimal、BigInteger、JsonNode 类型。
ArrayNode addAll(ArrayNode other) 用于添加给定数组的所有子节点
ArrayNode addNull() 该方法将在此数组节点的末尾添加 null 值。
ArrayNode addArray() 构造新的 ArrayNode 子节点,并将其添加到此数组节点的末尾
ObjectNode addObject() 构造一个新的 ObjectNode 字节的,并将其添加到此数组节点的末尾

Jsonson 注解设置 POJO 属性

1、ObjectMapper 序列化 POJO 对象为 json 字符串时,Date 日期类型默认会转为 long 长整型,json 字符串反序列化为 POJO 时自动将长整型的日期转为 Date 类型。

2、Map 对象序列化为 json 字符串时,Map 中的日期值也会默认转为 long 长整型, ObjectMapper.readValue(String content, Class valueType):反序列化为 Map 对象时,长整型的日期仍旧是长整型,不会转回 Date。ObjectMapper.readTree(String content) 反序列化为 json 节点时,原来 Map 中的长整型的日期也会是长整型。

3、JsonNode 节点对象 put 数据时,有 8 种基本数据类型以及 String、BigDecimal、BigInteger,但是没有 Date 类型,所以日期类型只能通过 Long 长整型设置,但是转 POJO 对象时仍然会自动转为 Date 类型。

4、Google 的 gson 默认不会序列化对象中值为 null 的字段,而 jackson 则不管值是否为 null,都会序列化。

5、@JsonFormat 注解加到指定对象的属性上可以指定日期序列化的格式。

6、JsonInclude(JsonInclude.Include.NON_NULL) 添加到 POJO 对象上,表示对值为 null 的属性不进行序列化。

API 演示源码:

https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/jackson/Book.java

https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/jackson/AnnotationTest.java

Guess you like

Origin blog.csdn.net/ToBeMaybe_/article/details/117038691