如何解决使用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()
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。