JAXB布尔值,大写为TRUE / FALSE,返回null

时间:2018-03-08 07:45:27

标签: java jaxb cxf jaxb2

我在Java 8上使用Apache CXF 2.7.11实现的一些Java第一个SOAP服务存在问题。当TRUE作为值传递时,值变为null。当以小写形式传递true时,同样适用。

我看到另一个线程,其中扩展XmlAdapter<String, Boolean>的类和@XmlJavaTypeAdapter已经解决了问题,但是生成的WSDL类型已经从xs:boolean更改为xs:string。这意味着布尔值应该由消费者作为字符串传递。在我的情况下这是不可接受的。

JAXB类:

@XmlRootElement(name = "myPojo")
public class MyPojo {
    @XmlElement(name = "myField")
    private Boolean myBoolean;

    @XmlJavaTypeAdapter(CustomBooleanAdapter.class)
    public void setMyBoolean(Boolean bool) {
        myBoolean = bool;
    }

    public Boolean getMyBoolean()  {
        return myBoolean;
    }
}

生成的WSDL类型

<xs:complexType name="myPojo">
    <xs:sequence>
        <xs:element minOccurs="0" name="myField" type="xs:string"/>
    </xs:sequence>
</xs:complexType>

现在,当我在服务上运行WSDL2Java时,生成的类myField将被创建为String而不是Boolean。

有没有办法在生成的WSDL中保持类型不变?

1 个答案:

答案 0 :(得分:6)

  

当TRUE作为值传递时,值变为null。

这是正确的。 对于XML中的布尔值,TRUE不是有效值。见XML Schema Specification

  

3.2.2.1词汇表示

     

定义为 boolean 的数据类型的实例可以具有   遵循法律文字{ true,false,1,0 }。

如果您使用CustomBooleanAdapter(我认为它看起来有点像这样),

public static class CustomBooleanAdapter extends XmlAdapter<String, Boolean> {

  @Override
  public Boolean unmarshal(String s) throws Exception {
    return "TRUE".equals(s);
  }

  @Override
  public String marshal(Boolean b) throws Exception {
    if (b) {
      return "TRUE";
    }
    return "FALSE";
  }
}

您在规范之上定义了自定义逻辑。适配器将String转换为布尔值,这就是您的字段生成为字符串的原因(它甚至表示XmlAdapter<String, Boolean>中的字符串)。

原则上,您要求的XmlAdapter<Boolean,Boolean>不会使用大写值&#34; TRUE&#34;。

所以要么使用xs:string和TRUE,要么使用xs:boolean和true。 我确实认为你应该使用规范中适当的布尔值。

相关问题