Здесь маленький 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;
}
}
< /code>
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);
}
}
< /code>
{"someEnumProperty":"INSTANCE_ONE"}
< /code>
Now, let's imagine I need the enum to be serialized into instance_one
Код: Выделить всё
@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();
}
}
}
< /code>
{"someEnumProperty":"instance_one"}
< /code>
But what if I don't have such a write access to SomeClass
Подробнее здесь: https://stackoverflow.com/questions/779 ... f-the-enum