使用 Jackson 读取最外面的 JSON 对象而不是内部对象?

Read the outer-most JSON object but not the inner ones using Jackson?

这与 this 问题类似,但略有不同。

假设我有一个这样定义的 json 文档:

[
    { "type" : "Type1", 
      "key1" : "value1" },
    { "type" : "Type2", 
      "key2" : "value2" }
]

我想将此 json 文档读入字符串列表 (List<String>)。我只想将最外层的列表读入 Java List,列表中的 json 对象应该保留在列表中。结果应该等同于此(我忽略换行符等):

var myList = List.of("{\"type\": \"Type1\", \"key1\": \"value1\"}, {\"type\": \"Type2\", \"key2\": \"value2\"}")

请注意,我不想创建任何 DTO 来保存一些中间表示。我只希望“列表”下面的所有内容都“按原样”表示。

我怎样才能做到这一点?

我正在使用 Jackson 2.12.1。

如果您不想在 DTO 中保留中间表示,那么可以实现所需反序列化的一种方法是:

// Create a ObjectMapper (of type com.fasterxml.jackson.databind.ObjectMapper)
ObjectMapper mapper = new ObjectMapper();
// Read the json string into a List. This will be deserialized as a collection of LinkedhashMap
 List<LinkedHashMap> list = mapper.readValue(getInputString(), List.class);
//Iterate over the deserialized collection and create a JSONObject from every LinkedHashMap
 List<String> result = list.stream()
                           .map(map -> new JSONObject(map).toString())
                           .collect(Collectors.toList());

这将产生:

[{"key1":"value1","type":"Type1"}, {"key2":"value2","type":"Type2"}]

这种方法的缺点是,它会影响性能。