2014-11-25 101 views
0

我想解析包含兩個陣列的對象和那些之間的關係的JSON文件的一對多的關係傑克遜解析JSON,這是一個例子:在單一步驟

{ 
    "a": [ 
     { 
      "name": "one", 
      "id": 1 
     }, 
     { 
      "name": "two", 
      "id": 2 
     }, 
     { 
      "name": "three", 
      "id": 3 
     } 
    ], 
    "b": [ 
     { 
      "name": "cool", 
      "a_id": 1 
     }, 
     { 
      "name": "better", 
      "a_id": 1 
     }, 
     { 
      "name": "no_id", 
      "a_id": null 
     } 
    ] 
} 

我想將這些地圖映射到兩個實體AentityBentity,其中Aentity應包含Bentities的數組。

而且我還想要列出Bentities與null a_id。

這是可能與傑克遜在一個單一的解析?怎麼樣?

注意:我在問,因爲我必須解析的文件比較大。

回答

1

你可以實現你問由兼具您Bentityida_id屬性,如下所示:

public class JacksonParsing { 

    private static final String JSON = "{\n" + 
      " \"a\": [\n" + 
      "  {\n" + 
      "   \"name\": \"one\",\n" + 
      "   \"id\": 1\n" + 
      "  },\n" + 
      "  {\n" + 
      "   \"name\": \"two\",\n" + 
      "   \"id\": 2\n" + 
      "  },\n" + 
      "  {\n" + 
      "   \"name\": \"three\",\n" + 
      "   \"id\": 3\n" + 
      "  }\n" + 
      " ],\n" + 
      " \"b\": [\n" + 
      "  {\n" + 
      "   \"name\": \"cool\",\n" + 
      "   \"a_id\": 1\n" + 
      "  },\n" + 
      "  {\n" + 
      "   \"name\": \"better\",\n" + 
      "   \"a_id\": 1\n" + 
      "  },\n" + 
      "  {\n" + 
      "   \"name\": \"no_id\",\n" + 
      "   \"a_id\": null\n" + 
      "  }\n" + 
      " ]\n" + 
      "}"; 

    public static void main(String... args) throws IOException { 
     ObjectMapper objectMapper = new ObjectMapper(); 

     Aentity result = objectMapper.readValue(JSON, Aentity.class); 

     System.out.println(result.getB().get(0).getName()); 
    } 

    static class Aentity { 

     private List<Bentity> a; 
     private List<Bentity> b; 

     public Aentity() { 

     } 

     public List<Bentity> getA() { 
      return a; 
     } 

     public void setA(List<Bentity> a) { 
      this.a = a; 
     } 

     public List<Bentity> getB() { 
      return b; 
     } 

     public void setB(List<Bentity> b) { 
      this.b = b; 
     } 

    } 

    static class Bentity { 

     private String name; 
     private Integer id; 
     private Integer a_id; 

     public Bentity() { 

     } 

     public String getName() { 
      return name; 
     } 

     public void setName(String name) { 
      this.name = name; 
     } 

     public Integer getId() { 
      return id; 
     } 

     public void setId(Integer id) { 
      this.id = id; 
     } 

     public Integer getA_id() { 
      return a_id; 
     } 

     public void setA_id(Integer a_id) { 
      this.a_id = a_id; 
     } 
    } 

} 

然而,你可能會更好,其中Aentitynameid財產,而Bentity有一個namea_id屬性(即不同的類型)都包含由不同的父對象。