我有一个JSON文件,其中包含我需要用于创建对象的2个值。 像这样:
{
"name": ["Adam", "Bart"],
"surname": ["White","Brown"]
}
我想使用这两个属性来创建一个包含Person(name,surname)类型的两个对象的List。
我如何使用杰克逊实现这一目标?
答案 0 :(得分:1)
您可以使用自定义反序列化器实现此目的:
我使用了这个Person
类:
public class Person
{
public String name;
public String surName;
public Person (String name, String surName) {
this.name = name;
this.surName = surName;
}
public String toString() {
return name + " " + surName;
}
}
这是自定义的Json反序列化器:
@SuppressWarnings("serial")
public class PersonListDeserializer extends StdDeserializer<List<Person>>
{
public PersonListDeserializer() {
this(null);
}
public PersonListDeserializer(Class<?> vc) {
super(vc);
}
@Override
public List<Person> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
List<Person> returnList = new ArrayList<>();
JsonNode rootNode = jp.getCodec().readTree(jp);
// expecting to find to arrays under root:
ArrayNode nameNode = (ArrayNode)rootNode.get("name");
ArrayNode surnameNode = (ArrayNode)rootNode.get("surname");
// build the return list from arrays
for (int i = 0 ; i < nameNode.size() ; i++) {
returnList.add(new Person(nameNode.get(i).toString(), surnameNode.get(i).toString()));
}
return returnList;
}
}
全部放在一起:
public static void main(String[] args)
{
String jsonString = "{ \"name\": [\"Adam\", \"Bart\"], \"surname\": [\"White\",\"Brown\"] }";
SimpleModule module = new SimpleModule();
// Note: the custom deserializer is registered to invoke for every List in input!
module.addDeserializer(List.class, new PersonListDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
try {
// instructing jackson of target generic list type
CollectionType personListType = TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class);
@SuppressWarnings("unchecked")
List<Person> personList = (List<Person>)mapper.readValue(jsonString, personListType);
System.out.println(personList);
} catch (IOException e) {
e.printStackTrace();
}
}
输出符合预期:
["Adam" "White", "Bart" "Brown"]