Binding a JSON to a Java class using JAXB

空扰寡人 提交于 2019-12-08 10:46:56

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1261593/binding-a-json-to-a-java-class-using-jaxb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!