简体   繁体   中英

Checkbox in JHipster

I have a checkbox in the html

<input type="checkbox" class="form-control" name="myflag" [(ngModel)]="myEntity.myflag" id="field_myflag">

The field (myflag) on DB has 2 possible value [OK, KO] and these 2 values are defined in an enumeration:

@Enumerated(EnumType.STRING)
@Column(name = "MYFLAG")
private MYFLAGENUM myflag;

so:

public enum MYFLAGENUM {
   OK, KO
}

Every time I try to save, I reach an exception:

WARN 888 --- [ XNIO-7 task-5] .mmaExceptionHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of myproject.hipster.testing.domain.enumeration.MYFLAGENUM out of VALUE_FALSE token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of myproject.hipster.testing.domain.enumeration.MYFLAGENUM out of VALUE_FALSE token at [Source: (PushbackInputStream); line: 1, column: 37] (through reference chain: myproject.hipster.testing.domain.MYENTITY["myflag"])

It seems VALUE_FALSE (or VALUE_TRUE) could not be converted to 'KO' (or 'OK'). So I create a converter, but I see it is not called. How can I manage my own "boolean" value with JHipster checkbox?

Try

...
@JsonDeserialize(using = OkKoDeserializer.class)
private MYFLAGENUM myflag;

and:

public class OkKoDeserializer extends StdScalarDeserializer<MYFLAGENUM> {
public OkKoDeserializer() {
    super(MYFLAGENUM.class);
}

@Override
public MYFLAGENUM deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String value = p.getValueAsString();
    if ("VALUE_FALSE".equalsIgnoreCase(value)) {
        return MYFLAGENUM.KO;
    }
    if ("VALUE_TRUE".equalsIgnoreCase(value)) {
        return MYFLAGENUM.OK;
    }

    throw new IllegalArgumentException("value " + value + " is not parseable to a MYFLAGENUM");
}
}

This way you tell the framework to use a special strategy to convert the input value to the enum value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM