当使用 Jackson 库序列化一个字符串列表时,它正确地提供了一个 JSON 字符串数组:
<mapper>.writeValue(System.out, Arrays.asList("a", "b", "c"));
[ "a", "b", "c" ]
但是,字符串被我们代码中的一个类包装/封闭:
public static class StringWrapper {
protected final String s;
public String getS() {
return s;
}
public StringWrapper(final String s) {
this.s = s;
}
}
当序列化“字符串包装器”列表时,我希望得到与上面相同的输出。现在我得到:
<mapper>.writeValue(System.out, Arrays.asList(new StringWrapper("a"), new StringWrapper("b"), new StringWrapper("c")));
[ {
"s" : "a"
}, {
"s" : "b"
}, {
"s" : "c"
} ]
最方便的方法是什么?如果可能,反序列化也应该有效。
最佳答案
您可以在单个 getter 上使用 @JsonValue
@JsonValue
public String getS() {
return s;
}
来自javadoc,
Marker annotation similar to javax.xml.bind.annotation.XmlValue that indicates that results of the annotated "getter" method (which means signature must be that of getters; non-void return type, no args) is to be used as the single value to serialize for the instance. Usually value will be of a simple scalar type (String or Number), but it can be any serializable type (Collection, Map or Bean).
关于java/jackson - 不要序列化包装类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27691560/