I use Kotlon class enums with Spring/Hibernate and 99.9% of the time they do what I want when these values are serialized into a JSON. The 0.1% case is what I’m dealing with now, I need a leading number character, which Kotlin (like all languages I know of) doesn’t allow in an enum.
The “name” property is final and can’t be overriden. Is there some other way to set what the name string is? I can override toString() fine but apparently that’s not what the JSON serializer is using.
Add @Serializable
annotation to the enum and add @SerialName("<JsonName>")
annotation to each enum value as needed.
Reference : SerialName for Enums
2 Likes
kotlinx-serialization looks like an alternative to the current Jackson-based stuff I’m using now, but @SerialName pointed me in the right direction. In my project just adding @JsonProperty to the enum entry makes it work.
Trying custom serialization in a spring boot application, and I cannot figure out the way how to handle custom enum representations.
enum class VoltageLevel(@get:JsonValue val s: String) {
HIGH("h"),
MEDIUM("m"),
LOW("l")
}
I use it in the following controller:
@RestController
class MapController(private val mapElementRepository: MapElementRepository) {
@GetMapping("/map-elements/view-window", produces = [MediaType.APPLICATION_JSON_VALUE])
fun index(
// other parameters
@RequestParam voltageLevels: Array<VoltageLevel>?
): MapElementResult {
// ...
}
}
On the swagger UI, the values are ok (h, m and v), but when I fire a request, I get
Could not resolve parameter [5] in public foobar.mapservice.MapElementResult foobar.mapservice.MapController.index(java.math.BigDecimal,java.math.BigDecimal,java.math.BigDecimal,java.math.BigDecimal,foobar.mapservice.NetworkType,foobar.mapservice.VoltageLevel,int): Failed to convert value of type ‘java.lang.String’ to required type ‘foobar.mapservice.VoltageLevel’; Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam foobar.mapservice.VoltageLevel] for value ‘h’
Same error if I try this way:
enum class VoltageLevel {
@JsonProperty("h")
HIGH,
@JsonProperty("m")
MEDIUM,
@JsonProperty("l")
LOW
}
Any clues?
Thanks