[英]Read the outer-most JSON object but not the inner ones using Jackson?
This is similar to this question but it's a little different.这与此问题相似,但略有不同。
Let's say I have a json document defined like this:假设我有一个 json 文档定义如下:
[
{ "type" : "Type1",
"key1" : "value1" },
{ "type" : "Type2",
"key2" : "value2" }
]
I want to read this json document into a list of strings ( List<String>
).我想将此 json 文档读入字符串列表(
List<String>
)。 I only want to read the outer-most list into the Java List
, the json objects inside the list should be left as-is inside the list.我只想将最外面的列表读入 Java
List
中,列表中的 json 对象应按原样保留在列表中。 The result should be equivalent to this (I ignore newlines etc):结果应该与此等效(我忽略换行符等):
var myList = List.of("{\"type\": \"Type1\", \"key1\": \"value1\"}, {\"type\": \"Type2\", \"key2\": \"value2\"}")
Note that I don't want to create any DTO to hold some intermediate representation.请注意,我不想创建任何 DTO 来保存一些中间表示。 I just want everything below the "list" to be represented "as-is".
我只想“按原样”表示“列表”下方的所有内容。
How can I achieve this?我怎样才能做到这一点?
I'm using Jackson 2.12.1.我正在使用 Jackson 2.12.1。
If you don't want to hold intermediate representation in a DTO, then one way in which the required deserialization can be achieved is:如果您不想在 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());
This will produce:这将产生:
[{"key1":"value1","type":"Type1"}, {"key2":"value2","type":"Type2"}]
Downside of this approach is, it takes a hit on performance.这种方法的缺点是,它会影响性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.