Home > Mobile >  Failed to convert boolean to enum using Jackson
Failed to convert boolean to enum using Jackson

Time:12-02

I have following java class in a Springboot application

public enum Status {
    
    DISABLED(false),
    
    ENABLED(true);
    
    private final boolean enabled;
    
    Status(boolean value){
        this.enabled = value;
    }

    public boolean value() {
        return this.enabled;
    }   
    
    /*
    @JsonValue public boolean jsonValue() { return enabled; }
    
    Error: Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `com.q.demo.model.Status` from Boolean value (token `JsonToken.VALUE_TRUE`); 
    
    */
    
    /*
    public static Status forValue(@JsonProperty("enabled") Boolean status) {
        if (status == null) {
           return null;
        }
        if (Status.ENABLED.value() == status.booleanValue()) {
              return Status.ENABLED;
        } else {
             return Status.DISABLED;
        }
   }
   
   Error: Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Input mismatch reading Enum `com.q.demo.model.Status`: properties-based `@JsonCreator` ([method com.q.demo.model.Status#forValue(java.lang.Boolean)]) expects JSON Object (JsonToken.START_OBJECT), got JsonToken.VALUE_TRUE;
   */

}

public class User {
    
    private Long userId;
    
    private String userName;
    
    private String role;
    
    private String password;
    
    private Status enabled;

    //Getters and setters

}

I would like to serialize/deserialize json given below to the enum

{ "userName" : "usrer", "role" : "role", "password" : "psw", "enabled" : true }

I am not successful by using either @JsonProperty(which accepts String only) or @JsonValue (given in the code as commented line with error message) or @Jsconcreator (again code and error message given in the commented section. Can somebody give me a pointer? Jackson version is 2.13.0. Thank you.

CodePudding user response:

All you need at this point is a way to tell Jackson to convert from and to your enum. You can combine @JsonValue and @JsonCreator inside your Status enum:

@JsonValue
public boolean value() {
    return this.enabled;
}

@JsonCreator
public static Status of(boolean b) {
    return b ? ENABLED : DISABLED;
}

@JsonValue (on the instance method) tells Jackson what value to use when serializing. The @JsonCreator annotation on that static method tells Jackson that the boolean taken from JSON can be used to resolve the corresponding enum value.

  • Related