Srinivas Srinivas - 3 years ago 132
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
to return the
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

Answer Source

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) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download