Srinivas Srinivas - 3 months ago 10
JSON Question

Map JSON string array to List<String> using Jackson

I have following JSON returned from server.

String json = {
"values": ["name","city","dob","zip"]
};


I want to use
ObjectMapper
to return the
List<String>
values. Something like:

List<String> response = mapper.readValue(json, List.class)


I have tried several ways but none of them worked. Any help is appreciated.




Edit: I don't want additional wrapper objects. I want to straight away get the
List<String>
out.

Answer

You could define a wrapper class as following:

public class Wrapper {

    private List<String> values;

    // Default constructor, getters and setters omitted
}

Then use:

Wrapper wrapper = mapper.readValue(json, Wrapper.class);
List<String> values = wrapper.getValues();

If you want to avoid a wrapper class, try the following:

JsonNode valuesNode = mapper.readTree(json).get("values");

List<String> values = new ArrayList<>();
for (JsonNode node : valuesNode) {
    list.add(node.asText());
}