2016-12-21 6 views
1

オブジェクトを作成するために必要な2つの値を含むJSONファイルがあります。このよう :2つ以上のプロパティを使用して1つのオブジェクト属性を作成する

{ 
    "name": ["Adam", "Bart"], 
    "surname": ["White","Brown"] 
} 

私はPerson型(名、姓)の2つのオブジェクトを含むリストを作成するには、これらの2つのプロパティを使用したいと思います。

私はこれをjacksonを使用してどのように達成できますか?

答えて

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"]