簡體   English   中英

反序列化后從嵌套的JSON中檢索值

[英]Retrieving values from nested JSON after de-serialization

我正在嘗試通過Chrome的Advanced REST Client中的JSON字符串測試REST服務。 我在這里有一個嵌套的JSON。 我將其作為字符串並將其映射到我的POJO類:

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

在這里, addressString保存下面給出的JSON String

{
 "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();
    }
}

在這里,我只能檢索第二個條目

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

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

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

但這是編譯器不接受的。 請注意,所有條目本質上都是動態的,並且(鍵,值)對隨用戶輸入而變化。 關於如何在此示例中檢索所有條目的任何建議。

據我了解,也許您需要研究兩件事:

  1. 為什么location的數據類型是Map<String, ?> 因為從您的JSON字符串中, location類型是ArrayList ,對吧? 如果要使其成為Map ,請使用一些字符串,例如: {"location" : "\\"key\\":\\"value\\""} 如果要使其成為List ,請刪除值周圍的“”

  2. 另一件事是,您似乎想要一個層次結構來描述某些地理結構。 假設,在Asia我們有IndiaChina ,在India我們有Bengaluru ,在China我們有Chengdu 因此, Asia的價值也應為包含IndiaChina兩項的List 因此,您應該在此處刪除[ ][ ] ,我認為這也是您只能檢索第二個條目的原因。

    在此處輸入圖片說明

以下是我的測試代碼,我修改了您的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");
    }
}

然后所有條目和級別都確定。 也許您可以嘗試一下。

希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM