gpt4 book ai didi

java/jackson - 不要序列化包装类

转载 作者:搜寻专家 更新时间:2023-11-01 01:21:14 25 4
gpt4 key购买 nike

当使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com