用Jackson序列化数组 [英] Serializing array with Jackson
本文介绍了用Jackson序列化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在序列化以下模型:
I'm serializing the following model:
class Foo {
private List<String> fooElements;
}
如果 fooElements
包含字符串'one','two'和'three。 JSON包含一个字符串:
If fooElements
contains the strings 'one', 'two' and 'three. The JSON contains one string:
{
"fooElements":[
"one, two, three"
]
}
如何让它看起来像这样:
How can I get it to look like this:
{
"fooElements":[
"one", "two", "three"
]
}
推荐答案
我得到了它通过添加自定义序列化器来工作:
I got it working by adding a custom serializer:
class Foo {
@JsonSerialize(using = MySerializer.class)
private List<String> fooElements;
}
public class MySerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
List<String> fooList = (List<String>) value;
if (fooList.isEmpty()) {
return;
}
String fooValue = fooList.get(0);
String[] fooElements = fooValue.split(",");
jgen.writeStartArray();
for (String fooValue : fooElements) {
jgen.writeString(fooValue);
}
jgen.writeEndArray();
}
}
这篇关于用Jackson序列化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文