且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JAXB返回null而不是空字符串

更新时间:2023-02-06 13:11:31

我认为您的XML看起来或多或少像这样:

I think your XML looks more or less like this:

    <myElement></myElement>

不幸的是,这意味着您传递空字符串

This, unfortunately, means, that you are passing an empty string.

如果你想传递 null ,你有两个选择:

If you want to pass null you have two options:


  1. 根本不传递此标记(您的XML根本不应包含< myElement /> 标记)。

  2. 使用 xsi:nil

  1. Do not pass this tag at all (your XML should not contain <myElement/> tag at all).
  2. Use xsi:nil.

如果使用 xsi:nil ,首先必须将xml元素(在XSD文件中)声明为 nilable ,就像这样:

If using xsi:nil, first you have to declare your xml element (in XSD file) as nilable, like this:

    <xsd:element name="myElement" nillable="true"/>

然后,在里面传递 null 值XML执行此操作:

Then, to pass the null value inside XML do this:

    <myElement xsi:nil="true"/>

或者这个:

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

这样,JAXB知道你要传递 null 而不是空字符串。

This way, JAXB knows, that you are passing null instead of an empty String.