How do we change the serializing style with enum

Enum objects usually return their value data (no field data) when you serialize it. if you want to change this, you can use @JsonValue, @JsonFormat annotation in Jackson library that is the main part for serialization in Spring Framework.

@JsonValue

You can change the field to serialize with this annotation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

enum Season {
SPRING("S", "봄"), SUMMER("M", "여름"), FALL("F", "가을"), WINTER("W", "겨울");

Season(String code, String value) {
this.code = code;
this.value = value;
}

private final String code;
private final String value;

/* Jackson will use this value when it is serialized. */
@JsonValue
public String code() { return code; }

public String value() { return value; }
}

@JsonFormat(shape = JsonFormat.Shape.OBJECT)

If you want to serialize all of the fields in enum, this annotation will be helpful to you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Jackson will use all of the fields in enum. */
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
enum Season {
SPRING("S", "봄"), SUMMER("M", "여름"), FALL("F", "가을"), WINTER("W", "겨울");

Season(String code, String value) {
this.code = code;
this.value = value;
}

private final String code;
private final String value;

public String code() { return code; }
public String value() { return value; }
}
Share