Fastjson

Not to mention, made by Alibaba, it has had several serious security breaches, but it is still popular. Here’s how it handles enumerations.

<! -- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> < artifactId > fastjson < / artifactId > < version > 1.2.76 < / version > < / dependency >

Serialized to the Name () value

The default is to move nothing

import com.alibaba.fastjson.JSON; enum Gender { BOY, GIRL, UNKNOW } class User { private Integer id; private Gender gender; public User() { } public User(Integer id, Gender gender) { super(); this.id = id; this.gender = gender; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; }} public class mainTest {public static void main(String[] args) throws Exception User(1, Gender.BOY); String jsonString = JSON.toJSONString(user); System.out.println(jsonString); // {"gender":"BOY","id":1} // Deserialize object user = JSON.parseObject(jsonString, user.class); System.out.println(user.getGender()); // BOY } }

Serialized to the ordinal() value

Global Settings

If the code is the same as above, you need to add a line of code at the beginning, and any enumeration will be serialized to the ordinal() value

JSON.DEFAULT_GENERATE_FEATURE &= ~SerializerFeature.WriteEnumUsingName.mask;
/ / global Settings, enumeration serialized using ordinal () JSON. DEFAULT_GENERATE_FEATURE & = ~ SerializerFeature. WriteEnumUsingName. Mask; Ordinal () User User = new User(1, gender.boy); String jsonString = JSON.toJSONString(user); System.out.println(jsonString); // {"gender":0,"id":1} // Deserialize object user = JSON.parseObject(jsonString, user.class); System.out.println(user.getGender()); // BOY

Special setup

Only want to be effective for a single serialization. Simply call the overloaded method of JSON.tojonstring and add the configuration.

public static String toJSONString(Object object, int defaultFeatures, SerializerFeature... features)
Ordinal () User User = new User(1, gender.boy); String jsonString = JSON.toJSONString(user, JSON.DEFAULT_GENERATE_FEATURE & ~SerializerFeature.WriteEnumUsingName.mask); System.out.println(jsonString); // {"gender":0,"id":1} // Deserialize object user = JSON.parseObject(jsonString, user.class); System.out.println(user.getGender()); // BOY

Serialized to a custom property

Many people also like to define a private property for an enumeration. When serializing to JSON, they want to use this property as a value, so they need to define their own JSON serialization and deserialization implementations. FastJSON provides two interfaces. The user controls the serialization and deserialization behavior, which is too simple to cover here. Look at the code

  • ObjectSerializer
  • ObjectDeserializer

Definitions of serializers

import java.io.IOException; import java.lang.reflect.Type; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.ObjectSerializer; public class GenderEnumSerializer implements ObjectSerializer { @Override public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, Int features) throws IOException {// Convert the value to Gender Gender Gender = (Gender) Object; / / serialization for custom name attribute, output line serializer. Out. WriteString (gender. The getName ()); }}

Definition of deserializer

import java.lang.reflect.Type; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; public class GenderEnumDeserializer implements ObjectDeserializer { @SuppressWarnings("unchecked") @Override public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {String value = parseObject(String. Class); // For (Gender Gender: Gender.values()) {if (gender.getName().equals(value)) {return (T) Gender; }} // If no match is found, throw an exception or return null; } @Override public int getFastMatchToken() {return jsonToken.literal_string; }}

Object & Enumeration definition

Enum Gender {BOY (" male "), the GIRL (" female "), UNKNOW (" I don't know "); public final String name; Gender(String name) { this.name = name; } public String getName() { return name; } } class User { private Integer id; // Specifies the serialization of the enumeration. Deserialization implementation class @ JSONField (serializeUsing = GenderEnumSerializer. Class, deserializeUsing = GenderEnumDeserializer.class) private Gender gender; public User() { } public User(Integer id, Gender gender) { super(); this.id = id; this.gender = gender; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; }}

test

Public static void main(String[] args) throws Exception { GetName () User User = new User(1, gender.unknow); String jsonString = JSON.toJSONString(user); System.out.println(jsonString); // {"gender":" do not know ","id":1} // Deserialize object user = JSON.parseObject(jsonString, user.class); System.out.println(user.getGender()); // UNKNOW } }

The last

Obviously, the most flexible way to customize ObjectSerializer /ObjectDeserializer is to consider abstracting an interface so that all enumerations implement the interface. In this way, ObjectSerializer /ObjectDeserializer implementations can be reused very well for interfaces.


This paper first: https://springboot.io/t/topic…