gpt4 book ai didi

java - Java中如何获取数组中对象的键值

转载 作者:行者123 更新时间:2023-12-02 19:08:59 25 4
gpt4 key购买 nike

我正在尝试获取 json 数组 响应的键和值。我想映射每个键并获取其值。目前我正在循环我的响应结果。

public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

JSONArray jsonArray = (JSONArray) map;

for (Object o : jsonArray) {
JSONObject json = new JSONObject((Map) o);

for (Object obj : json.entrySet()) {
Map.Entry entry = (Map.Entry) obj;

System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}

这是数组中的对象列表

[
{
"uniqueName": "INVinv0001-5179",
"documentType": "Invoice",
"description": "INVinv0001-5179",
"assignedDate": "2020-10-22",
"approver": "10011618",
"email": "adrian.cabral@example.com",
"fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
"attachments": [
"AEz0ACMDZtZ!cnN"
]
},
{
"uniqueName": "INVinv0001-5179",
"documentType": "Invoice",
"description": "INVinv0001-5179",
"assignedDate": "2020-10-22",
"approver": "10003025",
"email": "dummy@example.com",
"fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
"attachments": [
"AEz0ACMDZtZ!cnN"
]
}
]

我一直收到这个错误。

java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class org.json.simple.JSONObject 

最佳答案

尝试将 map 对象转换为 JSONArray 而不是 JSON 对象。它会给你 JSONObject 直接使用。

public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

JSONArray json = (JSONArray) map;
for (int i=0; i < json.length(); i++) {
JSONObject e = json.get(i);

System.out.println(e);
}
}

关于java - Java中如何获取数组中对象的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64618801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com