杰克逊XML地图重复元素组

时间:2018-09-06 15:03:25

标签: java xml jackson

使用杰克逊,我必须创建一个可以编组为遵循XML的java类

<Root>
   <Key>key1</Key>
   <Value>value1</Value>
   <Key>key2</Key>
   <Value>value2</Value>
   ...
</Root>

以下课程已关闭,但KeyValue的顺序不正确。

@JacksonXmlRootElement(localName = "Root")
class Root {
    @JacksonXmlProperty(localName = "Key")
    private String[] keys;
    @JacksonXmlProperty(localName = "Value")
    private String[] values;
}

如何创建以正确顺序映射到重复元素对的类?

1 个答案:

答案 0 :(得分:0)

我做到了!借助自定义序列化程序。

首先,根元素:

@JacksonXmlRootElement(localName = "Root")
class Root {
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Wrapper> keyValueList;
    // getters, setters
}

KeyValue对的包装器类:

@JsonSerialize(using = WrapperSerializer.class)
class Wrapper {
    private String key;
    private String value;
    // getters, setters, all args constructors
}

和序列化器:

public class WrapperSerializer extends StdSerializer<Wrapper> {
    public WrapperSerializer() {
        this(Wrapper.class);
    }

    protected WrapperSerializer(Class<Wrapper> t) {
        super(t);
    }

    @Override
    public void serialize(Wrapper value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeRaw(new StringBuilder()
                .append("<Key>")
                .append(value.getKey())
                .append("</Key>")
                .append("<Value>")
                .append(value.getValue())
                .append("</Value>")
                .toString());
    }
}

让我们测试一下:

Root ref = new Root();
ref.setKeyValueList(Arrays.asList(
        new Wrapper("k1", "v1"),
        new Wrapper("k2", "v2")));
XmlMapper xmlMapper = new XmlMapper();
String output = xmlMapper.writeValueAsString(ref);
System.out.println(output);

结果:

<Root><Key>k1</Key><Value>v1</Value><Key>k2</Key><Value>v2</Value></Root>