英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论