1. Java默认的枚举序列化

springboot 的 jackson 进行枚举的序列化时候,默认是返回枚举的name属性。

1
2
3
4
5
public enum Gender {
MAN(1,"男"),
WOMAN(2,"女");
}
// 序列化结果:仅输出 "MAN" 或 "WOMAN" 的字符串形式。
1
2
3
4
5
6
7
8
import com.fasterxml.jackson.databind.ObjectMapper;

public static void main(String[] args) throws JsonProcessingException{
List<Gender> genders = List.of(Gender.MALE, Gender.FEMALE);
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(genders));
}

执行结果

1
2
序列化结果:
["MALE","FEMALE"]

如果我们希望让枚举和普通对象一样进行json序列化,展示枚举的具体属性信息。那么有如下方案

2. @JsonValue

2.1 在get方法上使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import com.fasterxml.jackson.annotation.JsonValue;

public enum Gender {
MALE(1, "男"),
FEMALE(2, "女");

private final int code;
private final String description;

Gender(int code, String description) {
this.code = code;
this.description = description;
}

// 在 getter 方法上使用 @JsonValue
@JsonValue
public int getCode() {
return code;
}
}

1
2
序列化结果:
[1,2]

注意:只能在一个字段或方法上使用 @JsonValue 注解

2.2 让 @JsonValue 返回一个 Map 或自定义对象

你可以写一个方法,将需要返回的字段封装起来,然后在这个方法上加 @JsonValue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import com.fasterxml.jackson.annotation.JsonValue;

public enum Gender {
MALE(1, "男"),
FEMALE(2, "女");

private final int code;
private final String description;

Gender(int code, String description) {
this.code = code;
this.description = description;
}

@JsonValue
public Map<String, Object> toMap() {
Map<String, Object> map = new HashMap<>();
map.put("code", code);
map.put("description", description);
return map;
}
}
1
2
序列化结果:
[{"code":1,"description":"男"},{"code":2,"description":"女"}]

3. 使用 @JsonFormat(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import com.fasterxml.jackson.annotation.JsonValue;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Gender {
MALE(1, "男"),
FEMALE(2, "女");

private final int code;
private final String description;

Gender(int code, String description) {
this.code = code;
this.description = description;
}
}
1
2
序列化结果:
[{"code":1,"description":"男"},{"code":2,"description":"女"}]