Java / jackson - don't serialize the packaging class

When serializing a list of strings with the Jackson library, it provides the correct array of JSON strings:

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

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

However, the lines are wrapped / wrapped in 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 the string wrapper list, I would like to have the same result 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 way to do this? If possible, deserialization should also work.

+4
source share
2 answers

You can use @JsonValuefor your one recipient

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

From javadoc,

, javax.xml.bind.annotation.XmlValue, , "" ( ; non-void return type, no args) . (String Number), (Collection, Map Bean).

+8

. StringWrapper, @JsonValue .

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

, :

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

Source: https://habr.com/ru/post/1569313/


All Articles