There is another way you might be interested in, partly similar to accepted answer but can be written as one-liner (line breaks should help with understanding).
Input JSON:
{
"values": ["name", "city", "dob", "zip"]
}
Code snippet:
String json = "{\"values\":[\"name\",\"city\",\"dob\",\"zip\"]}";
ObjectMapper mapper = new ObjectMapper();
List<String> list = Arrays.asList(
mapper.convertValue(
mapper.readTree(json).get("values"),
String[].class
)
);
list.forEach(System.out::println);
This code snippet outputs the following:
name
city
dob
zip
Please note that Arrays.asList() returns a list of fixed size because it is backed by a given array. To get a resizable list just wrap it like that:
List<String> resizableList = new ArrayList<>(
Arrays.asList(new String[] {"a", "b", "c"})
);
Of course this solution can be adapted to more complex cases, not just Strings.
For example, for a given POJO User:
class User {
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return String.format(
"[User = {id: %d, name: \"%s\"}]",
id,
name
);
}
}
and input JSON:
{
"values": [{
"id": 1,
"name": "Alice"
}, {
"id": 2,
"name": "Bob"
}
]
}
following code snippet:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"values\":[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"}]}";
List<User> list = Arrays.asList(
mapper.convertValue(
mapper.readTree(json).get("values"),
User[].class
)
);
list.forEach(System.out::println);
yelds the following output:
[User = {id: 1, name: "Alice"}]
[User = {id: 2, name: "Bob"}]