How to send Enum data inside request object

Viewed 99

I have created an enum like the below to store static dropdown value.

 @JsonFormat(shape = JsonFormat.Shape.OBJECT)
    public enum Days {
        MONDAY(1,"Monday"), TUESDAY(2,"Tuesday"),THURSDAY(4,"Thursday"), FRIDAY(5,"Friday"), SATURDAY(6,"Saturday"), 
        SUNDAY(7,"Sunday");
        
        private final Integer key;
        private final String value;
    
        Days(Integer key, String value) {
            this.key = key;
            this.value = value;
        }
    
        public Integer getKey() {
            return key;
        }
    
        public String getValue() {
            return value;
        }
    }

I have written a below endpoint to list enum data as a JSON response

@GetMapping("/getenums")
    public List<Days> getenums() {
        return Arrays.asList(Days.values());
    }

which results in an array of JSON Objects like below

 [{"key":1,"value":"Monday"},{"key":2,"value":"Tuesday"},{"key":4,"value":"Thursday"},{"key":5,"value":"Friday"},{"key":6,"value":"Saturday"},{"key":7,"value":"Sunday"}]

I have sample domain like below

 public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long userId;
        private String name;
        private Days day;
        private Month month;
    }

Below is my controller,

@PostMapping("/user")
  public User createInstructor(@RequestBody User user) {        
    return userRepository.save(user);       
}

While trying to save the user using the below request data getting bad request how can I resolve this

{
    "name": "Pradeep",
   "day": {
        "key": 1,
        "value": "Monday"
    },
    "month": "JUNE"
}
1 Answers

If you really want to return the complete enum object in your REST API then one solution could be adding a custom deserializer to it:

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Days {
   MONDAY(1,"Monday"), TUESDAY(2,"Tuesday"),THURSDAY(4,"Thursday"), FRIDAY(5,"Friday"), SATURDAY(6,"Saturday"), 
   SUNDAY(7,"Sunday");
   
   private final Integer key;
   private final String value;

   Days(Integer key, String value) {
       this.key = key;
       this.value = value;
   }

   public Integer getKey() {
       return key;
   }

   public String getValue() {
       return value;
   }

   @JsonCreator
   public static Days fromObject(Map<String, Object> obj) {
      if (obj != null && obj.containsKey("key") && obj.containsKey("value")) {
          Integer key = obj.get("key");
          String value = obj.get("value");

          if (key != null) {
            for (Days day : Days.values()) {
                if (key.equals(e.getKey())) {
                  return day;
                } else {
                  return null;
                }
            }
          }
          return null;
      }
      return null;
   }
}

Additionally, you might want to tell Hibernate how to store your Enum in the database. You can use @Enumerated(EnumType.STRING) for that as follows:

public class User {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long userId;
   private String name;
   @Enumerated(EnumType.STRING)
   private Days day;
   private Month month;
}

This will store it as a String. The other option is ORDINAL, which will persist the Enum as an Integer.

Related