Binding a JSON to a Java class using JAXB

Question!

I have the following JSON, where can be either true or false:

{"flag1":<boolean value>, "flag2":<boolean value>}

And I have tried to bind it to a Java class using Jersey and the following JAXB annotations:

@XmlRootElement
public class MyClass {
    @XmlElement(name = "flag1", type = Boolean.class)
    private Boolean flag1;
    @XmlElement(name = "flag2", type = Boolean.class)
    private Boolean flag2;

    ...
}

The problem is that when I assign a non-boolean value to 'flag1' or 'flag2', like in the example below, JAXB automatically assigns a false value to the 'flag1' and 'flag2' fields of MyClass.

{"flag1":"foo", "flag2":"bar"}

Is there a way to annotate 'MyClass' so that when JSON's 'flag1' and 'flag2' are not boolean I get an exception?



Answers

It looks like Jersey is simply using Boolean.valueOf, which treats everything other than a literal "true" as false. Since JavaScript doesn't have a notion of variable type, this is an arguably valid behavior.

An XML mapping, by comparison, is based on a schema definition, which does have a very specific notion of boolean values.


Not having used Jersey (or JAXB since the 1.x days), I'm wondering if you have to annotate the actual variables, or if you could annotate the setters. Or perhaps you could provide a setter that takes a String and parses it, instead of / along with a setter that takes a boolean.

By : kdgregory


What you showed would work the way you want (throw an exception) if you used pure Jackson JAX-RS provider. It does accept some variations (1 and 0, since some languages do not have native boolean type), but not things that have no meaningful equivalent.

Alternatively, as suggested, a setter method with type String would make sense, since then you could manually control conversions.

By : StaxMan


This video can help you solving your question :)
By: admin