自定义Jackson库的CSV序列化

huangapple go评论72阅读模式
英文:

Custom serialisation for CSV with Jackson

问题

这里我需要将Product对象序列化为CSV格式。尝试运行时,我收到了“CSV生成器不支持属性的对象值(嵌套对象)”的错误。当在较低级别对象上添加@JsonUnwrapped注释后,仍然在某些情况下遇到相同的错误。

它不应该忽略一切并调用properties字段的自定义序列化程序吗?看起来它完全忽略了这个方法。我该如何解决这个问题?

顺便说一下,由于XML转换的原因,我不能更改代码结构。

谢谢,

英文:

So, imagine I have following Java classes:

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();
                }
            });
        }
    }
}

What I need here is to serialize the Product object to CSV. When trying to run it, I get CSV generator does not support Object values for properties (nested Objects) error. When adding @JsonUnwrappped annotation to lower level objects, I still get stuck at some point with the same error.

Shouldn't it ignore everything and call the custom serializer for the properties field? It looks like it completely ignores this method. How do I fix that?

Btw, I can't change the code structure because of the XML conversion.

Thanks,

答案1

得分: 1

当前你的代码生成的 JSON 大致如下:

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

我认为你只是在循环之前缺少了 jsonGenerator.writeArrayFieldStart("properties"),并且在循环之后缺少了 jsonGenerator.writeEndArray()

英文:

Currently the json that your code generates looks something like this:

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

I think you are just missing jsonGenerator.writeArrayFieldStart("properties") before the loop and jsonGenerator.writeEndArray() after the loop.

huangapple
  • 本文由 发表于 2020年8月19日 17:51:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63484367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定