'Is there a way to return an enum attribute by default during deserialization/serialization? [duplicate]

I want to return the attribute value as the default return type. I'm trying to avoid having my own getter & then storing the return value as an int in some object.

Ideally, some simple annotation to achieve this would be most convenient. Is there any form of @JsonFormat I might be able to use? I believe @Enumerated is just for persistence & only supports String & Ordinal anyways.

public enum Rank {
   NONE(-1)
   PRIVATE(1)
   CAPTAIN(2)
   GENERAL(3)
   
   private int value;   

   Rank(int value) { this.value = value; }
}
class RankDto {
   private String id;
   private Rank rank;
}

EDIT: After some digging I found out that using @JsonValue annotation on the field or on its getter method will result in that value by used for serialization/deserialization. The DB persisted value will not be affected.



Solution 1:[1]

Basically both Jackson and JPA have support for configuring how enums are (de) serialized by annotations.

Jackson: https://www.baeldung.com/jackson-serialize-enums

unsing @JsonFormat or maybe there are SerializationFeatures that can be set as default when configuring the ObjectMapper (by config file or programmatically)

JPA: https://www.baeldung.com/jpa-persisting-enums-in-jpa

using @Enumerated with String type

Both APIs support some kind of custom Serializer/Converter if you want to have full control over it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manuel Waltschek