I ask this because of one bug in Swagger UI. More on that is here.
Here, a small MRE:
package com.example.dynamicgateway.misc;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Getter
class SomeClass {
SomeEnum someEnumProperty = SomeEnum.INSTANCE_ONE;
enum SomeEnum {
INSTANCE_ONE, INSTANCE_TWO;
}
}
package com.example.dynamicgateway.misc;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
public class GenericTest {
@Test
@SneakyThrows
void test() {
ObjectMapper objectMapper = new ObjectMapper();
SomeClass someClass = new SomeClass();
String serializedSomeClass = objectMapper.writeValueAsString(someClass);
System.out.println(serializedSomeClass);
}
}
{"someEnumProperty":"INSTANCE_ONE"}
Now, let's imagine I need the enum to be serialized into instance_one instead. If I have write access to SomeClass, I could do this:
@NoArgsConstructor
@Getter
class SomeClass {
SomeEnum someEnumProperty = SomeEnum.INSTANCE_ONE;
enum SomeEnum {
INSTANCE_ONE, INSTANCE_TWO;
@Override
@JsonValue // this is the key
public String toString() {
return name().toLowerCase();
}
}
}
{"someEnumProperty":"instance_one"}
But what if I don't have such a write access to SomeClass? Maybe, I can somehow configure my ObjectMapper, can't I?
Continuing from https://stackoverflow.com/a/77977001/1180351:
If it's for serialization only, you can create a single serializer class that you can reuse for multiple enums:
Don't override
handledType; instead specify the type when the serializer is registered: