如何序列化双包装列表?

时间:2016-08-29 09:03:54

标签: java jackson jackson-dataformat-xml

我有以下课程

public class SomeObject {

    @JsonProperty("otherObjects")
    private List<Integer> otherObjects;

}

并希望将其序列化为以下XML

<someObject>
    <otherObjects>
        <objlist>
            <objref>123</objref>
            <objref>456</objref>
            <objref>789</objref>
        </objlist>
    </otherObjects>
</someObject>

我尝试创建自定义JsonSerializer:

private static class ObjectListSerializer extends JsonSerializer<List<Integer>> {

    @Override
    public void serialize(final List<Integer> integers, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeArrayFieldStart("objlist");

        for (Integer integer : integers) {
            jsonGenerator.writeNumberField("objref", integer);
        }

        jsonGenerator.writeEndArray();
    }

}

但是jsonGenerator期望一个值,我得到以下异常:

Exception in thread "main" com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value
    at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:1676)
    at com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator.writeFieldName(ToXmlGenerator.java:444)
    at com.fasterxml.jackson.core.JsonGenerator.writeArrayFieldStart(JsonGenerator.java:1409)
    at Playground$ObjectListSerializer.serialize(Playground.java:89)
    at Playground$ObjectListSerializer.serialize(Playground.java:85)
    at com.fasterxml.jackson.dataformat.xml.ser.XmlBeanPropertyWriter.serializeAsField(XmlBeanPropertyWriter.java:145)
    at com.fasterxml.jackson.dataformat.xml.ser.XmlBeanSerializerBase.serializeFields(XmlBeanSerializerBase.java:202)
    at com.fasterxml.jackson.dataformat.xml.ser.XmlBeanSerializer.serialize(XmlBeanSerializer.java:119)
    at com.fasterxml.jackson.dataformat.xml.ser.XmlSerializerProvider.serializeValue(XmlSerializerProvider.java:92)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3631)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2998)
    at Playground.main(Playground.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

如何解决此错误?

0 个答案:

没有答案