反序列化重复的密钥以使用Jackson列出 [英] Deserialize duplicate keys to list using Jackson
问题描述
我正在尝试将json反序列化为对象.但是,json有重复的键.我无法更改json,但我想使用Jackson将重复的键更改为列表.
I'm trying to deserialize json into object. However, the json has duplicate keys. I cannot change the json and I would like to use Jackson to change duplicate keys to a list.
这是我检索到的json的示例:
Here is an example of the json I retrieve:
{
"myObject": {
"foo": "bar1",
"foo": "bar2"
}
}
这是反序列化后我想要的:
And here is what I would like after deserialization:
{
"myObject": {
"foo": ["bar1","bar2"]
}
}
我这样创建了我的课程:
I created my class like so:
public class MyObject {
private List<String> foo;
// constructor, getter and setter
}
我尝试使用objectMapper
中的DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY
,但是它所做的只是获取最后一个键并将其添加到列表中,如下所示:
I tried to use DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY
from objectMapper
but all it does is taking the last key and add it to the list like this:
{
"myObject": {
"foo": ["bar2"]
}
}
这是我的objectMapper
配置:
new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
有没有一种方法可以使用杰克逊反序列化重复的键到列表?
Is there a way to deserialize duplicate keys to a list using Jackson?
推荐答案
您需要使用com.fasterxml.jackson.annotation.JsonAnySetter
批注:
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(jsonFile, Root.class);
root.getMyObject().getFoos().forEach(System.out::println);
}
}
class Root {
private MyObject myObject;
// getters, setters, toString
}
class MyObject {
private List<String> foos = new ArrayList<>();
@JsonAnySetter
public void manyFoos(String key, String value) {
foos.add(value);
}
// getters, setters, toString
}
在Java
一侧,您具有一个值列表:
On Java
side you have a list with values:
bar1
bar2
这篇关于反序列化重复的密钥以使用Jackson列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!