Mastering Enum JSON Serialization in Spring Boot 3: Practical Guide
This article explains how to control enum serialization and deserialization in Spring Boot 3, covering default output, @JsonFormat, @JsonValue, custom serializers and deserializers, as well as @JsonProperty, @JsonCreator, and practical code examples.
1. Introduction
In system development, JSON is widely used as a lightweight data exchange format, and enums in Java represent a fixed set of constants. Proper handling of enum serialization and deserialization is crucial, especially when business requirements demand custom mappings such as numeric codes or localized descriptions.
2. Practical Cases
2.1 Prepare Environment
Define a gender enum class:
public enum Gender {
UNKNOWN(0, "未知的性别"),
MALE(1, "男"),
FEMALE(2, "女"),
UNSTATED(9, "未说明的性别");
private final int code;
private final String name;
Gender(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() { return code; }
public String getName() { return name; }
}Define a User record that includes the enum field:
public record User(String name, int age, Gender gender) { }2.2 Default Enum Output
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping
public ResponseEntity<User> query() {
return ResponseEntity.ok(new User("Pack_xg", 33, Gender.MALE));
}
}Output:
2.3 Serialize Enum as JSON Object
Use @JsonFormat(shape = JsonFormat.Shape.OBJECT) on the enum to produce {"code":1,"name":"男"}.
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Gender { /* ... */ }Output:
2.4 Combine Enum with @JsonValue
Annotate the getter with @JsonValue to control serialization.
public enum Gender {
// ...
@JsonValue
public String getName() { return name; }
}Output:
2.5 Custom Enum Serializer
Implement a StdSerializer subclass and register it with @JsonSerialize.
public class GenderSerializer extends StdSerializer<Gender> {
public GenderSerializer() { super(Gender.class); }
@Override
public void serialize(Gender value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartObject();
gen.writeStringField("label", value.getName());
gen.writeNumberField("value", value.getCode());
gen.writeEndObject();
}
} @JsonSerialize(using = GenderSerializer.class)
public enum Gender { /* ... */ }Output:
2.6 Deserialize Enum
Standard deserialization works with numeric values.
@PostMapping
public ResponseEntity<User> save(@RequestBody User user) {
return ResponseEntity.ok(user);
}Output:
2.7 Use @JsonValue for Deserialization
Annotate getCode() with @JsonValue to serialize/deserialize by code.
public enum Gender {
@JsonValue
public int getCode() { return code; }
}Output:
2.8 Use @JsonProperty
Map custom JSON property names to enum constants.
public enum Gender {
@JsonProperty("unknow") UNKNOWN(0, "未知的性别"),
@JsonProperty("male") MALE(1, "男"),
@JsonProperty("female") FEMALE(2, "女"),
@JsonProperty("unknow_gender") UNSTATED(9, "未说明的性别");
}Output:
2.9 Use @JsonCreator
Define a factory method to create enum from a JSON field.
@JsonCreator
public static Gender fromCode(@JsonProperty("gender") int code) {
for (Gender g : Gender.values()) {
if (g.code == code) return g;
}
throw new IllegalArgumentException("Invalid gender code: " + code);
}Output:
2.10 Custom Deserializer
Implement StdDeserializer and register with @JsonDeserialize.
public class GenderDeserializer extends StdDeserializer<Gender> {
public GenderDeserializer() { super(Gender.class); }
@Override
public Gender deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
int code = p.getValueAsInt();
for (Gender g : Gender.values()) {
if (g.getCode() == code) return g;
}
return null;
}
} @JsonDeserialize(using = GenderDeserializer.class)
public enum Gender { /* ... */ }Output:
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
