Java FastJson 遍历 JSON 数组查找指定 ID 的 OS 版本
Java FastJson 遍历 JSON 数组查找指定 ID 的 OS 版本
假设存在一个 JSON 数组,其中包含多个对象,每个对象都有 'id' 和 'os_version' 属性。我们需要通过遍历这个数组,找到指定 'id' 的对象,并获取其对应的 'os_version' 属性值。
示例 JSON 数据:
{'images': [
{
'created_time': null,
'size': 20504903680,
'cloudinit': 'False',
'min_disk': 100,
'os_version': 'Ubuntu Server 20.04 64bit',
'os_type': 'Linux',
'name': 'EDR-Agent',
'description': null,
'os_bit': '64',
'id': '7978b501-59ad-43a5-b52c-328a3eb15e9c',
'min_ram': 8192,
'status': 'active'
},
{
'created_time': null,
'size': 34764488704,
'cloudinit': 'False',
'min_disk': 200,
'os_version': 'Windows Server 2016 64bit',
'os_type': 'Windows',
'name': 'win2016已加固20221212',
'description': null,
'os_bit': '64',
'id': '605c4e4e-a62b-4290-a405-b06fc2446223',
'min_ram': 4096,
'status': 'active'
}
]}
Java 代码实现:
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class JsonArrayExample {
public static void main(String[] args) {
String jsonString = '{'images': [{'created_time': null,'size': 20504903680,'cloudinit': 'False','min_disk': 100,'os_version': 'Ubuntu Server 20.04 64bit','os_type': 'Linux','name': 'EDR-Agent','description': null,'os_bit': '64','id': '7978b501-59ad-43a5-b52c-328a3eb15e9c','min_ram': 8192,'status': 'active'},{'created_time': null,'size': 34764488704,'cloudinit': 'False','min_disk': 200,'os_version': 'Windows Server 2016 64bit','os_type': 'Windows','name': 'win2016已加固20221212','description': null,'os_bit': '64','id': '605c4e4e-a62b-4290-a405-b06fc2446223','min_ram': 4096,'status': 'active'}]}';
JSONObject jsonObject = JSONObject.parseObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray('images');
String osVersion = null;
String searchId = '7978b501-59ad-43a5-b52c-328a3eb15e9c';
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject image = jsonArray.getJSONObject(i);
String id = image.getString('id');
if (id.equals(searchId)) {
osVersion = image.getString('os_version');
break;
}
}
System.out.println('os_version for id ' + searchId + ': ' + osVersion);
}
}
输出结果:
os_version for id 7978b501-59ad-43a5-b52c-328a3eb15e9c: Ubuntu Server 20.04 64bit
代码说明:
- 使用
JSONObject.parseObject(jsonString)将 JSON 字符串解析为JSONObject对象。 - 使用
jsonObject.getJSONArray('images')获取 'images' 数组。 - 使用
for循环遍历数组,并在循环中获取每个对象的 'id' 属性。 - 如果 'id' 与目标 'id' 相匹配,则获取该对象的 'os_version' 属性并保存到
osVersion变量中。 - 使用
break语句退出循环。 - 打印结果。
总结:
这段代码演示了如何使用 FastJson 库在 Java 中遍历 JSON 数组并查找指定 ID 的数据。这是一种常用的操作,可以帮助你从 JSON 数据中提取所需信息。
原文地址: https://www.cveoy.top/t/topic/nHNm 著作权归作者所有。请勿转载和采集!