2016-09-21 41 views
0

我想從Chrome的高級REST客戶端通過JSON字符串測試我的REST服務。我在這裏有一個嵌套的JSON。我以此爲字符串,並將其映射到我的POJO類:解序列化後從嵌套JSON中檢索值

ObjectMapper mapper = new ObjectMapper(); 
mapper.readValue(addressString, AddressPOJO.class); 

這裏,addressString持有JSON字符串低於

{ 
"location":"[{\"Asia\":[{\"India\":[{\"city\":\"Bengaluru\"}]}], [{\"India\":[{\"city\":\"Mumbai\"}]}]}] 
} 

我AddressPOJO給予了變量:

Map<String,?> location = new HashMap(); 

我正在從POJO檢索值

Map<String, ?> locations = addressPOJO.getLocation(); 
Iterator iterator1 = locations.entrySet().iterator(); 
while(iterator.hasNext()){ 
    Map.Entry pair1 = (Map.Entry)iterator1.next(); 
    Map<String,?> cities = (Map<String,?>) pair1.getValue(); 
    Iterator iterator2 = dataSets.entrySet().iterator(); 
    while(iterator.hasNext()){ 
     Map.Entry pair2 = (Map.Entry)iterator2.next(); 
     Map<String,?> city = (Map<String, ?>) pair2.getValue(); 
    } 
} 

在這裏,我只能retieve第二項,這

[{\"India\":[{\"city\":\"Mumbai\"}]}] 

我需要檢索的所有條目。我也嘗試使用這樣的MultiMap

MultiMap cities = (MultiMap) pair1.getValue(); 

但是這不被編譯器接受。請注意,所有條目都是動態的,並且(鍵,值)對根據用戶的輸入而改變。任何建議如何在本例中檢索所有條目。

回答

0

從我的理解,也許有您需要考慮兩兩件事:

  1. 爲什麼的location數據類型是Map<String, ?>?因爲從您的JSON字符串中,location的類型是ArrayList,對不對?如果您想將其設置爲Map,請使用以下字符串:{"location" : "\"key\":\"value\""}。如果要將其設置爲List,請刪除圍繞該值的「」
  2. 另一件事是,你似乎想要一個層次結構來描述一些地理結構。比方說,在Asia我們有IndiaChina,並在India我們有Bengaluru和在China我們有城市Chengdu。因此,Asia的值也應該是List,其中包含IndiaChina兩個項目。所以你應該刪除][這裏,我認爲這也是你只能夠檢索第二個條目的原因。 enter image description here

以下是我的測試代碼,我修改您的JSON字符串和location數據類型。

Location.java

public class Location { 
    private List location; 

    public List getLocation() { 
     return location; 
    } 

    public void setLocation(final List location) { 
     this.location = location; 
    } 
} 

TestJSON。java

public class testJson { 
    private static ObjectMapper mapper = new ObjectMapper(); 

    public static void main(final String[] args) throws JsonParseException, JsonMappingException, IOException { 
     final String locationString = "{\"location\":[{\"Asia\":[{\"India\":[{\"city\":\"Bengaluru\"}]}, {\"India\":[{\"city\":\"Mumbai\"}]}]}]}"; 
     final Location location = mapper.readValue(locationString, Location.class); 

     System.out.println("finish"); 
    } 
} 

然後所有條目和級別都可以。也許你可以試試看。

希望這會有所幫助。

+0

感謝您的回覆。對不起,我必須提到我將所有'['字符從JSON中移除,然後將其映射到POJO。我的前端人可能使用數組來生成JSON,因此'['。另外,我在這裏給出的例子並不是我正在處理的確切的事情。我只是給了一些樣本措辭。所以,如上所述,我不止一次地獲得關鍵「印度」。它不會是獨一無二的。我現在通過用'_'和一些隨機數來追蹤它。讓我知道我是否可以在不使用隨機數的情況下處理它。再次感謝。 –

+0

嗨,Abhiram,無論如何,我認爲你最好不要使用「地圖」,因爲在你的例子中,位置字符串不是地圖而是「列表」。如果您想使用map,請嘗試「LinkedHashMap」,因爲它始終是ObjectMapper代表對象的方式。 –