You could create an Ordinal Enum just like next:
public enum Color {
Green,
Blue,
Red
//and so on
}
Then you would need a custom deserializer, you just need to do something like the next (specifying field name
to the key and writeString
to the color value):
public class ColorSerializer extends StdSerializer<Color> {
public ColorSerializer() {
this(null);
}
public ColorSerializer(Class<Color> t) {
super(t);
}
public void serialize(Color value, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
gen.writeStartObject();
gen.writeFieldName("val");
gen.writeString(value.toString());
gen.writeEndObject();
}
}
You must specify to use this serializer to your enum using annotation @JsonSerialize
above Color enum as next:
@JsonSerialize(using = ColorSerializer.class)
public enum Color {
//....
}
Finally, you must change your typecolorName
property to Color
enum type instead of String and annotate as Enumarted Ordinal type (JPA)
@Enumerated(EnumType.ORDINAL)
Color color;