Jackson FasterXML POJO 到 XML 列表

Jackson FasterXML POJO to XML list

我正在使用 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>

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

您可以使用 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"。