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

时间:2018-09-27 06:30:18

标签: java arrays json list json-simple

我正在使用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)]

1 个答案:

答案 0 :(得分: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)]