繁体   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