I'm having a piece of that selecting data in JSON and I want to convert it to 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);
From the code, I get the below result:
[{"entry":"1","count":1},{"entry":"2","count":1},{"entry":"3","count":1}]
I try to code using
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);
and getting the result :
[{"entry":"2","count":3}]
My question is how am I going to put the result into an ArrayList in Java like below :
[(1,1),(2,1),(3,1)]
You need go through your
JSONArray
, cast each element into aJSONObject
and extract theentry
andcount
values from each one, then make a string out of them and add to your list:This outputs: