What's the canonical way to get the following enum to write the intValue
when mapping this to a String with a normal ObjectMapper
? As-is, it writes the text (for example DEBUG
) but I want it to write a 1 (JSON number).
enum class SEVERITY(val intValue: Int) {
DEBUG(1),
VERBOSE(2),
INFO(3),
WARN(4),
ERROR(5),
CRITICAL(6)
}
What's the canonical way to get the following enum to write the intValue
when mapping this to a String with a normal ObjectMapper
? As-is, it writes the text (for example DEBUG
) but I want it to write a 1 (JSON number).
enum class SEVERITY(val intValue: Int) {
DEBUG(1),
VERBOSE(2),
INFO(3),
WARN(4),
ERROR(5),
CRITICAL(6)
}
Share
Improve this question
edited Mar 17 at 12:39
jonrsharpe
122k30 gold badges268 silver badges476 bronze badges
asked Mar 17 at 12:32
mikebmikeb
11.4k8 gold badges69 silver badges132 bronze badges
1 Answer
Reset to default 1Based on this answer, you can annotate a method with @JsonValue
that returns an Int
, and Jackson will use the return value of that method to write the JSON.
In this case, that method will be the getter for intValue
, which you can annotate like this:
enum class Severity(@get:JsonValue val intValue: Int) { ... }
You can also omit "get:
", in which case the annotation will be applied to the backing field of intValue
, which also works.