Reputation:
When serializing a list of string with Jackson library, it provides correctly a JSON array of strings:
<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.
Upvotes: 6
Views: 2082
Reputation: 19231
I see two possible options. If you own the StringWrapper
class you can simply add the @JsonValue
annotation on the getter.
@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());
Upvotes: 3
Reputation: 280178
You can use @JsonValue
on your single getter
@JsonValue
public String getS() {
return s;
}
From the 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).
Upvotes: 11