使用Jackson的CSV自定义序列化

问题描述

所以,假设我有以下java类

public class A {
    @JsonProperty("id")
    String id;

    @JsonProperty("name")
    String name;

    @JsonSerialize(using = PropertiesSerializer.class)
    @JsonUnwrapped
    Properties properties;
}

public class Properties {
    List<Property> properties;
}

public class Property {
    String key;
    String value;
}

class PropertiesSerializer extends JsonSerializer<Properties> {
    @Override
    public void serialize(Properties properties,JsonGenerator jsonGenerator,SerializerProvider serializerProvider) {
        if (properties != null && properties.getProperties() != null) {
            properties.getProperties().forEach(property -> {
                try {
                    jsonGenerator.writeStartObject();
                    jsonGenerator.writeStringField(property.getKey(),property.getValue());
                    jsonGenerator.writeEndobject();
                } catch (IOException e) {
                    e.printstacktrace();
                }
            });
        }
    }
}

在这里需要将Product对象序列化为CSV。尝试运行它时,出现CSV generator does not support Object values for properties (nested Objects)错误。在将@JsonUnwrappped注释添加到较低级别的对象时,我仍然会在某些时候停留在同一错误上。

它不应该忽略所有内容并为properties字段调用自定义序列化程序吗?看起来它完全忽略了此方法。我该如何解决

顺便说一句,由于XML转换,我无法更改代码结构。

谢谢

解决方法

当前,您的代码生成的json看起来像这样:

{
    "id": "myId","name": "myName",{
        "foo": "bar"
    },{
        "foo2": "bar2"
    },...
}

我认为您只是在循环之前错过了jsonGenerator.writeArrayFieldStart("properties"),而在循环之后错过了jsonGenerator.writeArrayEnd()