使用Jackson将JSON字符串数组映射到List

时间:2021-12-07 18:05:53

I have following JSON returned from server.

我有从服务器返回的以下JSON。

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

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

我想使用ObjectMapper返回List 值。就像是:

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.

编辑:我不想要额外的包装器对象。我想立即取出List

2 个解决方案

#1


4  

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) {
    values.add(node.asText());
}

#2


21  

The TypeFactory in Jackson allows to map directly to collections and other complex types:

Jackson中的TypeFactory允许直接映射到集合和其他复杂类型:

String json = "[ \"abc\", \"def\" ]";
ObjectMapper mapper = new ObjectMapper();

List<String> list = mapper.readValue(json, TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));

#1


4  

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) {
    values.add(node.asText());
}

#2


21  

The TypeFactory in Jackson allows to map directly to collections and other complex types:

Jackson中的TypeFactory允许直接映射到集合和其他复杂类型:

String json = "[ \"abc\", \"def\" ]";
ObjectMapper mapper = new ObjectMapper();

List<String> list = mapper.readValue(json, TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));