0

I have a boolean checkbox in my html page, like this:

<input type="checkbox" id="pnrCheckbox" name="includesPnr" value="true"/>
<!-- this field is autogenerated by spring as a workaround for something -->
<input type="hidden" name="_includesPnr" value="on"/>

When I send a Json string via Ajax to my controller, network traffic in my browser shows this form data:

_includesPnr: on

In my controller I use Jackson to deserialize the json back to my java model, which fails because it cannot map the _includesPnr property because of the underscore. If I manually map the the property like this

@JsonProperty(value="_includesPnr")
private Boolean includesPnr;

it still fails because 'on' is not a boolean value.

What do I have to do to send the property with the correct name and true/false instead of on/off?

hooch
  • 1,135
  • 1
  • 16
  • 31

1 Answers1

0

Try this for the @JsonProperty annotation: JSON field mapping for Java model

Then use a custom deserializer to convert "on" to "true"

In your case:

@JsonProperty("_includesPnr")
@JsonDeserialize(using = CustomBooleanDeserializer.class)
private Boolean includesPnr;

Then for CustomBooleanDeserializer (reference: http://tutorials.jenkov.com/java-json/jackson-annotations.html)

public class CustomBooleanDeserializer extends JsonDeserializer<Boolean> {

   @Override
   public Boolean deserialize(JsonParser jsonParser,
        DeserializationContext deserializationContext) throws
    IOException, JsonProcessingException {
       return ("on".equals(jsonParser.getText())) ? true : false;
   }
}

(Code is untested)

Otomatonium
  • 211
  • 2
  • 6