簡體   English   中英

在沒有 Java Object class 的情況下提取值的最佳方法是什么

[英]What is the best way to extract a value without having a Java Object class

我有一個像下面這樣的字符串

{
    "id": "abc",
    "title": "123.png",
    "description": "fruits",
    "information": [
        {
            "type": "apple",
            "url": "https://apple.com"
        },
        {
            "type": "orange",
            "url": "https://orange.com"
        }
    ],
    "versions": 0
}

我想獲取url的值,其中type: orange information中的列表可能並不總是與上述數據中出現的順序相同。 我知道我可以在 python 中使用json.loadsjson.dump輕松完成。

我正在嘗試使用JsonNodeobjectMapper.readTree.at("/information")來完成 java 但我無法以一種巧妙巧妙的方式通過這一點來獲取列表並獲取 url,其中類型 = 橙色。

這很簡單

使用JSON庫並使用該庫解析響應。 然后只獲取您需要的值和屬性...

與您的案例相關的示例:

// Get your Json and transform it into a JSONObject

JSONObject mainObject = new JSONObject(yourJsonString); // Here is your JSON...

// Get your "information" array

JSONArray infoArray = mainObject.getJSONArray("information"); // Here you have the array

// Now you can go through each item of the array till you find the one you need

for(int i = 0 ; i < infoArray.length(); i++)
{
    JSONObject item = participantsArray.getJSONObject(i);

    final String type = item.getString("type");
    final String url = item.getString("url");

    if(type.equals("orange"))
    {
        // DO WHATEVER YOU NEED
    }
}

暫無
暫無

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

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