【问题标题】:What is the best way to extract a value without having a Java Object class在没有 Java Object 类的情况下提取值的最佳方法是什么
【发布时间】:2021-11-28 06:02:05
【问题描述】:

我有一个类似下面的字符串

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

我想获取url 的值,其中type: orangeinformation 中的列表可能并不总是与上面数据中出现的顺序相同。我知道我可以使用 json.loadsjson.dump 在 python 中轻松完成。

我正在尝试使用JsonNodeobjectMapper.readTree.at("/information") 来做java,但我无法以一种巧妙巧妙的方式超越这一点来获取列表并获取type = orange 的url。

【问题讨论】:

标签: java arrays json objectmapper


【解决方案1】:

这很简单

使用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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    相关资源
    最近更新 更多