0

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.

turbofood
  • 192
  • 9
  • Can you show the dto holding some `Rank`, that should ultimately be (de-)serialized? – Turing85 May 02 '22 at 22:05
  • @Turing85 Sure, its just a basic obj though – turbofood May 02 '22 at 22:07
  • Why don't you just use the Integer type on the dto and write a mapper if the client needs this representation? I think it's more explicit. Other than that I believe this article sums up your options pretty well: https://www.baeldung.com/jackson-serialize-enums – Manuel Waltschek May 02 '22 at 22:13
  • There is no easy annotation to define a value for the field if it is `null` (although there is a [github issue](https://github.com/FasterXML/jackson-future-ideas/issues/39) for this feature). We can work around this by writing a custom Serializer and Deserializer. An example is shown on [`ingrom.com`](https://ingrom.com/qa/307888/setting-default-values-to-null-fields-when-mapping-with-jackson-java). – Turing85 May 02 '22 at 22:13
  • @ManuelWaltschek Well its not just the Dto actually, but the entity structure itself. I don't want to be storing a bunch of Integers instead of the actual enum all over the place. – turbofood May 02 '22 at 22:15
  • Okay but these should be two different configurations / implementations. One for jackson and one for jpa serialization. What do you expect to be stored? I usually persist the name of the enum and normally frameworks are smart enough to deserialize them again. – Manuel Waltschek May 02 '22 at 22:19

1 Answers1

0

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.

Manuel Waltschek
  • 515
  • 1
  • 6
  • 23