在没有Java Object类的情况下提取值的最佳方法是什么?



我有一个像下面这样的字符串

{
"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,但我无法通过一个聪明的整洁的方式来获取列表和获取url,其中type = orange。

这很简单

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

相关内容

最新更新