为对象显示 null -JSON- JAXB

Van*_*ran 5 java api json jaxb marshalling

我想在 JSON 表示中将空对象编组为空。但是,现在,如果对象为空,我看不到 JSON 中的元素。

Example:
@XmlAccessType(FIELD)
@XmlType(name="foo" propOrder={"foo"}
class foo{
@XmlElement
      private Integer foo;
      private Integer another_foo;
..

getter()
setter()

}
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我将 foo 元素设置为 null。

但是 JSON 表示不显示响应中的元素。

响应看起来像这样

"foo" :{
 "another_foo":something
}
Run Code Online (Sandbox Code Playgroud)

我尝试将 xml 元素属性设置为 nillable true。(@XmlElement(nillable=true)

这使得响应看起来像,

"foo" :{
 "another_foo" : something
 "foo":{nil :true}
}
Run Code Online (Sandbox Code Playgroud)

我希望它像,

    "foo" :{
     "another_foo":something
     "foo" : null
    }
Run Code Online (Sandbox Code Playgroud)

这里做错了什么?

Sta*_*Man 4

首先,JAXB 不支持 JSON。它是一个 XML API。所以你可能正在使用一个框架(我的猜测:JAX-RS 实现,比如 Jersey)?有必要知道您正在使用哪一种来提供更多帮助。

假设这样,问题是,包如何使用 JAXB 注释来指导 JSON 序列化。有些基本上将对象转换为 XML(逻辑结构或完整 xml),然后使用约定转换为 JSON。由于 XML 和 JSON 之间的数据模型不同,这可能会导致数据丢失。

现在:大多数 JAX-RS 实现的简单解决方案是根本不使用基于 JAXB 注释的方法,而是使用特定于 JSON 的序列化程序,例如Jackson的 JacksonJsonProvider (Jackson 实际上也可以使用 JAXB 注释)。默认情况下,它将包含属性的空值,但如果您想抑制空值,这是可以配置的。

这里是JavaDoc,展示了如何将 Jackson 提供程序(指定 FEATURE_POJO_MAPPING 进行配置)与 Jersey 一起使用,如果这可能有帮助的话。