【问题标题】:JAXB and Jersey list resolution?JAXB 和 Jersey 列表解析?
【发布时间】:2010-02-05 02:49:23
【问题描述】:

我定义了以下 XSD 来生成一些 jaxb 对象。效果很好。

<xsd:element name="Person" type="Person" />

<xsd:complexType name="Person">
    <xsd:sequence>
        <xsd:element name="Id" type="xsd:int" />
        <xsd:element name="firstName" type="xsd:string" />
        <xsd:element name="lastName" type="xsd:string" />
    </xsd:sequence>
</xsd:complexType>

<xsd:element name="People">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="Person" minOccurs="0" maxOccurs="unbounded"
                type="Person" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

我使用 Spring RowMapper 将数据库中的行映射到 Person 对象。所以,我最终 使用 List 对象,该对象不是 People 对象。 I People 对象在内部有一个 List

然后在我的泽西资源类中我有:

@GET
@Path("/TheListOfPeople")
public List<Person> getListOfPeople() { 
    List<Person> list = dao.getList();
    return list;
}

返回的XML是:

<?xml version="1.0" encoding="UTF-8" standalone="yes" >
<people>
  <Person>...</Person>
  <Person>...</Person>
  <Person>...</Person>
  <Person>...</Person>
</people>

我的问题是如何在 XML 中将 List 映射到 People。此外,元素是“人”(大写 P)而不是“人”(小写 P)。似乎它根本没有真正使用 XSD。

编辑这与这个问题有某种关系:JAXB Collections (List<T>) Use Pascal Case instead of Camel Case for Element Names

【问题讨论】:

    标签: java spring jaxb jersey


    【解决方案1】:

    似乎并没有真正使用 完全是 XSD

    那是因为它没有。 JAXB 仅在使用 XJC 生成代码时使用模式;之后它就没有用了,在运行时它只使用注释(它也可以用于验证,但这与这里无关)。

    您的 REST 方法正在返回 List&lt;Person&gt;,而 Jersey 正在尽最大努力将其转换为 XML,将其包装在 &lt;people&gt; 中。你没有告诉它使用 People 包装类,它自己也无法猜测。

    如果要生成&lt;People&gt; 包装器元素,则需要为其提供People 包装器类:

    @GET
    @Path("/TheListOfPeople")
    public People getListOfPeople() { 
        People people = new People();
        people.getPerson().addAll(dao.getList()); // or something like it
    
        return people ;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 2012-12-01
      • 2012-11-09
      相关资源
      最近更新 更多