【问题标题】:Should a web service response include empty values?Web 服务响应是否应该包含空值?
【发布时间】:2013-09-11 09:32:49
【问题描述】:

在调用 Web 服务时,我得到 XML 格式的动态响应。

所以响应可能是:

<response>
<test1>test1</test1>
<test2>test1</test2>
<test3>test1</test3>
<test4>test1</test4>
</response>

或:

<response>
<test1>test1</test1>
<test2>test1</test2>
</response>

但我认为响应应该是静态的,以便 Java 类能够从 XML 中正确解组。

所以不是

<response>
<test1>test1</test1>
<test2>test1</test2>
</response>

这应该是:

<response>
<test1>test1</test1>
<test2>test1</test2>
<test3></test3>
<test4></test4>
</response>

这意味着我现在可以处理响应并检查丢失的数据。

我的想法正确吗?

【问题讨论】:

标签: web-services rest jaxb unmarshalling


【解决方案1】:

默认空表示

默认情况下,JAXB (JSR-222) 实现会将属性视为可选元素。因此,空值表示为文档中不存在的元素。

Null 的替代表示

或者,您可以通过在其上包含 xsi:nil="true" 属性来表示 null。这是通过使用 @XmlElement(nillable=true) 注释您的属性来实现的。

<date xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

无效的空表示

空元素不是 null 的有效表示。它将被视为一个空字符串,对所有非字符串类型都无效。

<date/>

更多信息


更新

所以 test1 test1 是 一个有效的响应,但字段 test3 和 test4 将被设置为 null ?

发生的情况是没有对对应于缺失节点的字段/属性执行任何操作。他们将保留默认值,默认初始化为null

Java 模型(根)

在下面的模型类中,我已将字段初始化为具有非 null 的值。

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Root {

    @XmlElement
    String foo = "Hello";

    String bar = "World";

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

演示

正在编组的文档&lt;root/&gt; 没有任何与模型类中映射的字段/属性相对应的元素。

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

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StringReader xml = new StringReader("<root/>");
        Root root = (Root) unmarshaller.unmarshal(xml);

        System.out.println(root.foo);
        System.out.println(root.bar);
    }

}

输出

我们看到输出的是默认值。这说明没有对缺席的节点进行集合操作。

Hello
World

【讨论】:

  • SO test1test1 是有效响应,但字段 test3 和 test4 将设置为 null ?跨度>
  • @user470184 - 我已经用一些应该有帮助的信息更新了我的答案。
【解决方案2】:

参考JAXB Marshalling with null fields 还有What's the purpose of minOccurs, nillable and restriction?

使用@XmlElement(nillable = true) 来显示那些空/空白值字段;但要特别注意您的日期字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多