Java JAXB返回null而不是空字符串

Java JAXB返回null而不是空字符串,java,jaxb,Java,Jaxb,如果内部XML属性值为空,则在解组时如何检索null值?现在,我在getter中检查null: public String getLabel() { if (label.isEmpty()) { return null; } else { return label; } } 但可能存在其他更优雅的方式吗 谢谢。我认为您的XML大致如下: <myElement></myElement> &l

如果内部XML属性值为空,则在解组时如何检索
null
值?现在,我在getter中检查
null

public String getLabel() {
    if (label.isEmpty()) {
        return null;
    }
    else {
        return label;
    }
}
但可能存在其他更优雅的方式吗


谢谢。

我认为您的XML大致如下:

    <myElement></myElement>
    <xsd:element name="myElement" nillable="true"/>
然后,要在XML中传递
null
值,请执行以下操作:

    <myElement xsi:nil="true"/>

或者这个:

    <myElement xsi:nil="true"></myElement>

通过这种方式,JAXB知道您传递的是
null
,而不是空字符串。

这是一个很好的方法,我建议您指定如何表示
null
。要编组
xsi:nil
,您需要将属性注释为(请参阅):

如果不想更改XML表示,则可以使用
XmlAdapter

清空字符串适配器

package forum10869748;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class EmptyStringAdapter extends XmlAdapter<String, String> {

    @Override
    public String unmarshal(String v) throws Exception {
        if("".equals(v)) {
            return null;
        }
        return v;
    }

    @Override
    public String marshal(String v) throws Exception {
        return v;
    }

}
演示

package forum10869748;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum10869748/input.xml");
        Foo foo = (Foo) unmarshaller.unmarshal(xml);

        System.out.println(foo.getLabel());
    }

}
input.xml

<?xml version="1.0" encoding="UTF-8"?>
<foo>
    <label></label>
</foo>

为什么null是更好的选择?在调用之后,不要检查字符串是否为null(为了避免NPE,您必须这样做),而是检查字符串是否为空,这样就完成了。这段代码非常有用,可以作为使用
JAXB
的示例。但在我看来,你在这里提出的建议是危险的。将空字符串视为空字符串而不通知契约中可能存在空字符串(
WSDL
XSD
)是一种猴子补丁,几乎可以肯定的是,总有一天会有人在调试时非常非常非常沮丧。如果你想同样对待空字符串和null,我建议使用@npe——我同意指定
@xmlement(nillable=true)
并在XML中显式表示null是最好的方法(我甚至对你的答案投了赞成票)。我为那些无法更改XML表示的人添加了这个答案。我不认为它是危险的,只要用户与空元素的含义一致。
package forum10869748;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum10869748/input.xml");
        Foo foo = (Foo) unmarshaller.unmarshal(xml);

        System.out.println(foo.getLabel());
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<foo>
    <label></label>
</foo>
null