1

我正在使用 FasterXML Jackson 实现通过 xml-databing 包将 POJO 转换为 XML 输出。我正在尝试实现此输出:

<MyRequest>
 <MySubRequest>4</MySubRequest>
 <MySubRequest>5</MySubRequest>
</MyRequest>

我的课程:

public class MySubRequest {

@JacksonXmlText
private String id;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public MySubRequest(String id) {
    super();
    this.id = id;
}

}

和:

@JacksonXmlRootElement
public class MyRequest {

private Collection<MySubRequest> MySubRequest;

public Collection<MySubRequest> getRequests() {
    return MySubRequest;
}

public void setRequests(Collection<MySubRequest> requests) {
    this.MySubRequest = requests;
}

}

我正在测试它:

ObjectMapper mapper = new XmlMapper();
MyRequest entity = new MyRequest();
Collection<MySubRequest> myIds = new ArrayList<>();
myIds.add(new MySubRequest("12"));
myIds.add(new MySubRequest("34"));
entity.setRequests(myIds);
mapper.writeValue(System.out, entity);

但输出是:

<MyRequest xmlns="">
 <requests>
  <requests>12</requests>
  <requests>34</requests>
 </requests>
</MyRequest>

我想知道的另一件事是如何强制输出区分大小写,即大写变量名。

4

1 回答 1

1

您可以使用JacksonXmlElementWrapper注释来忽略包装器。只需像这样使用它:

@JacksonXmlRootElement
class MyRequest {


    private Collection<MySubRequest> mySubRequest;

    public Collection<MySubRequest> getRequests() {
        return mySubRequest;
    }

    @JacksonXmlProperty(localName = "MySubRequest")
    @JacksonXmlElementWrapper(useWrapping = false)
    public void setRequests(Collection<MySubRequest> requests) {
        this.mySubRequest = requests;
    }

}

在这里,我使用JacksonXmlProperty注释将元素名称用作 xml 中的“MySubRequest”。

于 2015-08-03T09:16:50.447 回答