カスタムデシリアライザでこれを達成することができます
を私はこの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"]