将对象的 JSON 数组转换为 List<String>

我有一段 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)]


繁星点点滴滴
浏览 727回答 1
1回答

素胚勾勒不出你

您需要遍历您的JSONArray,将每个元素转换为 aJSONObject并从每个元素中提取entry和count值,然后从中创建一个字符串并添加到您的列表中:if (arrOne != null) {&nbsp; &nbsp; JSONObject entryCountJson;&nbsp; &nbsp; String entry, count;&nbsp; &nbsp; for (Object o : arrOne) {&nbsp; &nbsp; &nbsp; &nbsp; entryCountJson = (JSONObject) o;&nbsp; &nbsp; &nbsp; &nbsp; entry = String.valueOf(entryCountJson.get("entry"));&nbsp; &nbsp; &nbsp; &nbsp; count = String.valueOf(entryCountJson.get("count"));&nbsp; &nbsp; &nbsp; &nbsp; listOne.add("(" + entry + "," + count + ")");&nbsp; &nbsp; }}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)]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java