使用 Jackson ObjectMapper 将 JsonArray 映射到 List<Pojo>

Map JsonArray to List<Pojo> using Jackson ObjectMapper

我需要使用 Jackson 的 ObjectMapper 将表示为字符串的 Json 数组转换为 List<Pojo>

这是我所做的,但实际上不起作用:

public static <T> List<T> toList(String jsonString, Class<T> clazzType) {

    try {
      List<T> list = OBJECT_MAPPER.readValue(jsonString, new TypeReference<List<T>>() {});

      return list;

    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }

它 returns 是一个具有内部列表但并未真正构建预期的 Pojos 列表的对象。我看到一些使用反射的尝试,但我试图让它保持纯粹的 Jackson。

有什么想法吗??

您可以使用 TypeFactory 创建 CollectionLikeType。 例如像这样:

ObjectMapper objectMapper = new ObjectMapper();

CollectionLikeType collectionLikeType = objectMapper.getTypeFactory()
    .constructCollectionLikeType(List.class, String.class);

List<String> o = objectMapper.readValue("[\"hello\"]", collectionLikeType);

assertEquals(o, List.of("hello"));