Enum類型的序列化在JSON數據傳輸中非常常見,尤其是涉及到前端和后端數據交互時。對于Enum類型的序列化,有兩種方式,一種是使用字符串表示枚舉類型,另一種是使用整型表示枚舉類型。
如果使用字符串來表示Enum類型,在序列化過程中可以直接將枚舉類型的名稱作為JSON中對應屬性的值。代碼如下:
public enum UserType { ADMIN("管理員"), CUSTOMER("客戶"); private String desc; private UserType(String desc) { this.desc = desc; } public String getDesc() { return this.desc; } } public class User { private String userName; private UserType userType; //getter and setter } public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); User user = new User(); user.setUserName("tom"); user.setUserType(UserType.ADMIN); try { String json = objectMapper.writeValueAsString(user); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } } //輸出結果:{"userName":"tom","userType":"ADMIN"}
如果使用整型表示Enum類型,則需要對枚舉類型進行處理。代碼如下:
public enum UserType { ADMIN(1), CUSTOMER(2); private final int value; private UserType(int value) { this.value = value; } public int getValue() { return value; } public static UserType getTypeByValue(int value) { for (UserType type : UserType.values()) { if (type.value == value) { return type; } } return null; } } public class User { private String userName; private UserType userType; //getter and setter } public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(UserType.class, new UserTypeSerializer()); objectMapper.registerModule(module); User user = new User(); user.setUserName("tom"); user.setUserType(UserType.ADMIN); try { String json = objectMapper.writeValueAsString(user); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } } public class UserTypeSerializer extends JsonSerializer{ @Override public void serialize(UserType userType, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { if (userType != null) { jsonGenerator.writeNumber(userType.getValue()); } } } //輸出結果:{"userName":"tom","userType":1}
以上是Enum類型的序列化JSON的兩種方式,開發者可以根據不同情況選擇適合的方式。