Home > database >  Kotlin: Jackson Serialize an enums value
Kotlin: Jackson Serialize an enums value

Time:10-01

Using enum State:

enum class State(val desc: String) {
ACTIVE("In Use"),
INACTIVE("Not In Use")
}

and class Thing:

data class Thing {
  val name: String,
  val state: State
}

How would one use Jackson to serialize Thing such that "thing": { "name": "Thing's name", "state": "In Use"}?

I know of @JsonFormat(shape = JsonFormat.Shape.OBJECT) to annotate the State enum, but this results in "thing": { "name": "Thing's name", "state": {"state": "ACTIVE", "desc": "IN USE"} so isn't quite what I require.

Without any intervention the result is "thing": { "name": "Thing's name", "state": "ACTIVE"}

Any help appreciated

CodePudding user response:

You can use the @JsonValue annotation.

enum class State(@JsonValue val desc: String) {
    ACTIVE("In Use"),
    INACTIVE("Not In Use")
}
  • Related