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 a JSONObject
and extract the entry
and count
values from each one, then make a string out of them and add to your list:
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);
This outputs:
arrOne: [{"entry":"1","count":1},{"entry":"2","count":1},{"entry":"3","count":1}]
listOne: [(1,1), (2,1), (3,1)]