更快 XML 序列化而不使用 XML 中的字段类型

FasterXML serialization without using field type in XML

我正在努力实现以下目标 XML:

<model>
    <entry>
        <key>A</key>
        <value>1</value>
    </entry>
    <entry>
        <key>B</key>
        <value>2</value>
    </entry>
</model>

最接近的 POJO 模型我通过试验我的代码看起来像这样:

import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import static com.google.common.collect.Lists.newArrayList;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;

public class InsPersonFormTest {

    @JsonRootName("model")
    public static class Model extends ArrayList<Entry> {

        public Model(List<Entry> entries) { super(entries); }

        public List<Entry> getEntry() { return this; }
    }

    public static class Entry {

        String key;
        String value;

        public Entry(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public String getKey() { return key; }

        public String getValue() { return value; }       
    }

    @Test
    public void shouldSendPostRequest() throws JsonProcessingException {
        Model model = new Model(newArrayList(new Entry("A", "1"), new Entry("B", "2")));

        ObjectMapper xmlMapper = new XmlMapper();
        String xml = xmlMapper.writeValueAsString(model);

        assertThat(xml, equalTo(
                "<model>"
                + "<entry><key>A</key><value>1</value></entry>"
                + "<entry><key>B</key><value>2</value></entry>"
                + "</model>"));
    }
}

但它给了我

预期:

"<model><entry><key>A</key><value>1</value></entry><entry><key>B</key><value>2</value></entry></model>"

但是:是

"<model><item><key>A</key><value>1</value></item><item><key>B</key><value>2</value></item></model>"

如何将 item 更改为 entry 或使用最简单的 POJO 结构和更合适的 Map<String, String> 字段?

您是否尝试过注释条目 class?

@JsonRootName("entry")
public static class Entry {

    String key;
    String value;

    public Entry(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() { return key; }

    public String getValue() { return value; }       
}

不要让您的 Model class 成为 ArrayList 的子类型。而是使用组合

public static class Model {
    private ArrayList<Entry> entry;

    public Model(List<Entry> entries) {
        entry = entries; // or make a copy 
    }

    @JacksonXmlElementWrapper(useWrapping = false)
    public List<Entry> getEntry() {
        return entry
    }

}

ArrayList 是一个 List,Jackson 以一种有管理的方式处理 List

您需要添加 JacksonXmlElementWrapper 这样您就可以告诉 Jackson 不要包装结果 XML.

然后您可以使用

@JacksonXmlRootElement(/* custom */)

注释 Entry 并添加 XML 节点的本地名称和命名空间值。