gpt4 book ai didi

java - 将 JSON 对象数组转换为列表

转载 作者:行者123 更新时间:2023-11-30 05:59:23 25 4
gpt4 key购买 nike

我有一段 JSON 格式的选择数据,我想将其转换为 Java ArrayList。

String q = "SELECT attributes FROM common_attr_test";
PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(q);
preparedStatement.execute();
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
valueAttributes = rs.getString("attributes");
}

JSONObject obj=(JSONObject)JSONValue.parse(valueAttributes);
JSONArray arrOne=(JSONArray)obj.get("1");
System.out.println(arrOne);

从代码中,我得到以下结果:

[{"entry":"1","count":1},{"entry":"2","count":1},{"entry":"3","count":1}]

我尝试使用

进行编码
ArrayList<String> listOne = new ArrayList<String>();

if (arrOne != null) {
int len = arrOne.size();
for (int i=0;i<len;i++){
listOne.add(arrOne.get(i).toString());
}
}
System.out.println(arrOne);
System.out.println("\nlistOne:"+listOne);

并得到结果:

[{"entry":"2","count":3}]

我的问题是如何将结果放入 Java 中的 ArrayList 中,如下所示:

[(1,1),(2,1),(3,1)]

最佳答案

您需要检查 JSONArray,将每个元素转换为 JSONObject 并提取 entrycount值,然后用它们创建一个字符串并添加到您的列表中:

if (arrOne != null) {
JSONObject entryCountJson;
String entry, count;
for (Object o : arrOne) {
entryCountJson = (JSONObject) o;
entry = String.valueOf(entryCountJson.get("entry"));
count = String.valueOf(entryCountJson.get("count"));
listOne.add("(" + entry + "," + count + ")");
}
}
System.out.println("arrOne: "+arrOne);
System.out.println("listOne: "+listOne);

输出:

arrOne: [{"entry":"1","count":1},{"entry":"2","count":1},{"entry":"3","count":1}]
listOne: [(1,1), (2,1), (3,1)]

关于java - 将 JSON 对象数组转换为列表<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52530773/

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