Home > OS >  Enum class doesn't return values I need
Enum class doesn't return values I need

Time:10-05

I have created an enumerated class that contains 2 values. What I want is to create a controller that returns the enumerations that exist along with their values.

This is my Enum Class:

@Getter
public enum ModesEnum {

   ASSOCIATED ("A", "Associated"), DISASSOCIATED ("D", "Disassociated");

   private String key;
   private String value;

   private ModesEnum(String key, String value) {
       this.key = key;
       this.value = value;
   }

   @JsonValue
   public String getValor() {
       return value;
   }

   @JsonValue
   public String getKey() {
       return key;
   }

   private static final Map<String, String> mapClassEnum;

   static {
       mapClassEnum = new HashMap<>();
       Arrays.stream(values()).forEach(elem -> {
           mapClassEnum.put(elem.getValue(), elem.getKey());
           mapClassEnum.put(elem.getValue(), elem.getValor());
   });
}

My Controller class:

@GetMapping(value = "/modesEnum")
    public ResponseEntity<ModesEnum[]> getAll(){
        return new ResponseEntity<>(ModesEnum.values(), null, HttpStatus.OK);
    }

however when executing the controller it gives me the following error:

 Problem with definition of AnnotedClass ModesEnum Multiple 'as-value' properties defined ModesEnum #getKey() vs ModesEnum [0]

How can I return in my controller something like this JSON?:

{
   { key: "A", value : "Associated"},
   { key: "D", value : "Disassociated"}
}

CodePudding user response:

The JsonValue documentation says that only one method may be annotated with @JsonValue.

At most one method of a Class can be annotated with this annotation; if more than one is found, an exception may be thrown.

You can try to serialize both key and value in a toString() method (annotate toString() with @JsonValue).

Another option might be to use @JsonProperty on your enum instances:

@JsonProperty("associated")
ASSOCIATED ("A", "Associated"), 
@JsonProperty("disassociated")
DISASSOCIATED ("D", "Disassociated");
  • Related