[英]What is the best way to extract a value without having a Java Object class
I have a string like below我有一个像下面这样的字符串
{
"id": "abc",
"title": "123.png",
"description": "fruits",
"information": [
{
"type": "apple",
"url": "https://apple.com"
},
{
"type": "orange",
"url": "https://orange.com"
}
],
"versions": 0
}
I want to get the value of url
where type: orange
.我想获取url
的值,其中type: orange
。 The list in information
may not always be in same order as appearing in the data above. information
中的列表可能并不总是与上述数据中出现的顺序相同。 I know I could do it easily in python with json.loads
and json.dump
.我知道我可以在 python 中使用json.loads
和json.dump
轻松完成。
I am trying to do it java using JsonNode
and objectMapper.readTree.at("/information")
but I am unable to get past this point in a clever neat way to get the list and fetch the url where type = orange.我正在尝试使用JsonNode
和objectMapper.readTree.at("/information")
来完成 java 但我无法以一种巧妙巧妙的方式通过这一点来获取列表并获取 url,其中类型 = 橙色。
This is pretty straightforward这很简单
Use a JSON library and parse the response using the library.使用JSON库并使用该库解析响应。 Then get only the values and attributes that you need...然后只获取您需要的值和属性...
Example relevant to your case:与您的案例相关的示例:
// 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.