简体   繁体   English

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

[英]java/jackson - don't serialize wrapping class

When serializing a list of string with Jackson library, it provides correctly a JSON array of strings: 使用Jackson库序列化字符串列表时,它正确提供了一个JSON数组字符串:

<mapper>.writeValue(System.out, Arrays.asList("a", "b", "c"));

[ "a", "b", "c" ]

However, the strings are wrapped/enclosed by a class in our code: 但是,字符串由我们的代码中的类包装/包含:

public static class StringWrapper {
    protected final String s;

    public String getS() {
        return s;
    }

    public StringWrapper(final String s) {
        this.s = s;
    }
}

When serializing a list of "string wrapers", I would like to have the same output as above. 在序列化“字符串包装器”列表时,我希望获得与上面相同的输出。 Now I get: 现在我得到:

<mapper>.writeValue(System.out, Arrays.asList(new StringWrapper("a"), new StringWrapper("b"), new StringWrapper("c")));

[ {
  "s" : "a"
}, {
  "s" : "b"
}, {
  "s" : "c"
} ]

What is the most convenient method to do this? 这样做最方便的方法是什么? If possible, deserializing should work also. 如果可能,反序列化也应该起作用。

You can use @JsonValue on your single getter 你可以在你的单个getter上使用@JsonValue

@JsonValue
public String getS() {
    return s;
}

From the javadoc, 来自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 . 类似于javax.xml.bind.annotation.XmlValue的标记注释,表示带注释的“getter”方法的结果(这意味着签名必须是getter的结果;非void返回类型,没有args) 将被用作单个要为实例序列化的值 Usually value will be of a simple scalar type (String or Number), but it can be any serializable type (Collection, Map or Bean). 通常,value将是一个简单的标量类型(String或Number),但它可以是任何可序列化的类型(Collection,Map或Bean)。

I see two possible options. 我看到两种可能的选择。 If you own the StringWrapper class you can simply add the @JsonValue annotation on the getter. 如果您拥有 StringWrapper类,则只需在getter上添加@JsonValue注释即可。

@JsonValue
public String getS() { return s; }

If you are not allowed to change the object the following streaming solution works as well: 如果您不允许更改对象,则以下流式解决方案也可以正常工作:

mapper.writeValueAsString(listOfStringWrappers.stream().map(sw -> sw.getS()).toArray());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM