[Solved] Cannot deserialize instance of enum list spring boot exception

cannot-deserialize-instance-enum-list-spring-boot-exception-featured
cannot-deserialize-instance-enum-list-spring-boot-exception-blog

Cannot deserialize instance of enum list spring boot exception

Issue

When you are trying to map the POST request body with enum properties, then you must need to do @JsonCreator to map the enums with request body and the list of properties available in the enum.

Full Exception for reference

JSON parse error: Cannot deserialize instance of ‘com.ngdeveloper.posts.enums.PostType’ out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of ‘com.ngdeveloper.posts.enums.PostType’ out of START_OBJECT token at [Source: (PushbackInputStream); line 17, column 5] (through reference chain: com.ngdeveloper.dto.posts”

Solution

Issue code for reference

@Getter
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum PostType {
   NEW("NEW","New Post"),
   DRAFT("DRAFT", "Drafted Post");

 private String type;
 private String description;
  
  PostType(String type, String description){
     this.type = type;
     this.description = description;
  }
 
}

Fixed code for reference

Add the @JsonCreator annotation with the static method to map the json property with the enums.

@Getter
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum PostType {
   NEW("NEW","New Post"),
   DRAFT("DRAFT", "Drafted Post");

 private String type;
 private String description;
  
  PostType(String type, String description){
     this.type = type;
     this.description = description;
  }

   @JsonCreator
   static PostType findValue(@JsonProperty("type") String type, @JsonProperty("description") String description){
      return Arrays.stream(PostType.values()).filter(pt -> pt.type.equlas(type) && pt.description.equals(description)).findFirst().get();
}
 
}

Still “Cannot deserialize instance of enum list spring boot exception” comes ?

  • Then you may need compare the exact value of the enums are matching with the request body.
  • Do maven build and try once again!

Leave a Reply