This article describes the various operations of fastjson custom serialization.
1. What is fastjson?
fastjson is Alibaba's open source JSON parsing library that parses strings in JSON format, supports serialization of Java Bean s to JSON strings, and can also deserialize from JSON strings to JavaBean s.
2. How to Use
Add the following maven dependencies:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency>
3. fastjson default serialization
The fastjson entry class is com.alibaba.fastjson.JSON, and the simplest default serialization code is as follows:
User user = new User(); String str= JSON.toJSONString(user);
4. How to customize serialization
fastjson supports multiple ways to customize serialization.
1. Use serialized attribute SerializerFeature
Common SerializerFeature properties are as follows:
Name | Meaning |
---|---|
WriteNonStringKeyAsString | Convert to String if key is not String |
WriteNonStringValueAsString | Convert to String if value is not String |
WriteMapNullValue | Field with empty output |
WriteNullStringAsEmpty | Output''when String is null |
WriteNullNumberAsZero | Output 0 if number is null |
WriteDateUseDateFormat | Modify date format, yyyy-MM-dd |
Now that we have finished describing the common properties, let's take a look at the effect and create a new User class with the following code:
@Data public class User implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private Integer age; private String name; private String sex; private Date createDate; private Map<Integer, Integer> dataMap; }
Run the class code as follows:
public static void main(String[] args) { User user = new User(); user.setId(1000); user.setName("Java Broken thoughts"); user.setCreateDate(new Date()); Map<Integer, Integer> datamap = new HashMap<>(); datamap.put(1, 100); datamap.put(2, 200); user.setDataMap(datamap); System.out.println("Default serialization results:\n" + JSON.toJSONString(user)); System.out.println("Appoint WriteNonStringKeyAsString Serialization results:\n" + JSON.toJSONString(user, SerializerFeature.WriteNonStringKeyAsString)); System.out.println("Appoint WriteNonStringValueAsString Serialization results:\n" + JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString)); System.out.println("Appoint WriteMapNullValue Serialization results:\n" + JSON.toJSONString(user, SerializerFeature.WriteMapNullValue)); System.out.println("Appoint WriteNullStringAsEmpty Serialization results:\n" + JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty)); System.out.println("Appoint WriteNullNumberAsZero Serialization results:\n" + JSON.toJSONString(user, SerializerFeature.WriteNullNumberAsZero)); System.out.println("Appoint WriteDateUseDateFormat Serialization results:\n" + JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat)); }
Run result:
Default serialization results: {"createDate":1575038247084,"dataMap":{1:100,2:200},"id":1000,"name":"Java Fragmentation"} Specify WriteNonStringKeyAsString serialization results: {"createDate": 1575038247084, "dataMap": {"1": 100","2": 200},"id": 1000,"name":"Java Fragmentation"} Specify WriteNonStringValueAsString serialization results: {"createDate":1575038247084,"dataMap":{1:"100",2:"200"},"id":"1000","name":"Java Fragmentation"} Specify WriteMapNullValue serialization results: {age': null,'createDate': 1575038247084,'dataMap': {1:100,2:200},'id': 1000,'name','Java Fragmentation','sex': null} Specify WriteNullStringAsEmpty serialization results: {"createDate": 1575038247084, "dataMap": {1:100,2:200}, "id": 1000, "name", "Java Fragmentation", "sex": "} Specify WriteNullNumberAsZero serialization results: {age":0,"createDate":1575038247084,"dataMap":{1:100,2:200},"id":1000,"name":"Java Fragmentation"} Specify WriteDateUseDateFormat serialization results: {"createDate":"2019-11-29 22:37:27","dataMap":{1:100,2:200},"id":1000,"name":"Java Fragmentation"}
2. Use JSONField
JSONField is a comment for fastjson that can be used on fields or on getter/setter methods.
2.1 JSONField comment
The main contents of the note are as follows:
package com.alibaba.fastjson.annotation; public @interface JSONField { // Configure the order of serialization and deserialization to be supported after version 1.1.42 int ordinal() default 0; // Specify the name of the field String name() default ""; // Specify the format of the field, useful for date formats String format() default ""; // Is it serialized boolean serialize() default true; // Deserialization or not boolean deserialize() default true; }
2.2 JSONField Annotation Configuration
- Configure on Fields
@Data public class User implements Serializable { @JSONField(name = "_id") private Integer id; }
- Configure on getter/setter
@JSONField(name="_id") public Integer getId() { return id; } @JSONField(name="_id") public void setId(Integer id) { this.id = id; }
- Configure date formatting using format
@JSONField(format="yyyy-MM-dd") private Date createDate;
- Use serialize/deserialize to specify that fields are not serialized
@JSONField(serialize=false) private Integer age;
- Use ordinal to specify the order of fields
@JSONField(ordinal = 2) private String name;
Modify the code directly below to see the effect. The modified User class is as follows:
@Data public class User implements Serializable { private static final long serialVersionUID = 1L; @JSONField(name = "_id", ordinal = 3) private Integer id; @JSONField(serialize = false, ordinal = 4) private Integer age; @JSONField(ordinal = 1) private String name; @JSONField(ordinal = 2) private String sex; @JSONField(format = "yyyy-MM-dd", ordinal = 5) private Date createDate; }
The test class runs as follows:
Default serialization results: {age: 18,'createDate': 1575006127174,'id': 1000,'name':'Java Fragmentation'} Serialization results after using JSONField: {"name":"Java fragmentation", _id":1000,"createDate":"2019-11-29"}
As you can see from running the results, using the @JSONField annotation changes as follows:
- ID serialized to _id
- createDate formatted as yyyy-MM-dd
- The order of the fields after serialization is the same as that specified by ordinal
- Field age with serialize=false set is not serialized
The result is consistent with the expectation, indicating that there is no problem with custom serialization. By now, the function of fastjson custom serialization has been fully implemented. Welcome to leave a message if you have any questions.
Recommended reading
1.SpringBoot2.0 integrates WebSocket s for real-time push of back-end data!
2.1 minute to learn about MyBatis's dynamic SQL!
3.One minute to learn about Spring Security!
4.One minute to learn how to use mybatis-generator to automatically generate code!
5. Hand-held Seven Transaction Dissemination Behaviors of Spring in Actual War
Free Java-related materials are available within a time limit, covering technologies such as Java, Redis, MongoDB, MySQL, Zookeeper, Spring Cloud, Dubbo/Kafka, Hadoop, Hbase, Flink, high concurrent distribution, big data, machine learning, etc.
Pay free attention to the following public numbers: