问题描述
我有以下JSON,其中可以是true或false:
I have the following JSON, where can be either true or false:
{"flag1":<boolean value>, "flag2":<boolean value>}
我试图将它绑定到使用Jersey和以下JAXB注释的Java类:
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;
...
}
问题在于我为'flag1'或'flag2'分配了一个非布尔值,如下例所示,JAXB自动为MyClass的'flag1'和'flag2'字段分配一个false值。
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"}
有没有办法注释'MyClass',这样当JSON的'flag1'和'flag2'不是布尔值时我得到一个异常?
Is there a way to annotate 'MyClass' so that when JSON's 'flag1' and 'flag2' are not boolean I get an exception?
推荐答案
看起来泽西岛只是在使用,它将文字true以外的所有内容视为false。由于JavaScript没有变量类型的概念,因此这是一种可论证的有效行为。
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.
相比之下,XML映射基于模式定义,有一个非常具体的布尔值概念。
An XML mapping, by comparison, is based on a schema definition, which does have a very specific notion of boolean values.
自从1.x天以来没有使用过Jersey(或JAXB),我想知道你是否必须注释实际的变量,或者你是否可以注释setter。或者你可以提供一个setter,它接受一个 String
并解析它,而不是/与一个带有 boolean $ c $的setter一起c>。
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
.
这篇关于使用JAXB将JSON绑定到Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!