I am trying to execute a SELECT SQL
query and after that I need to loop through the ResultSet
and get the columns
and check whether the data I got back for those columns
is a Valid JSON String
or not.
Here columnsList
is an ArrayList
which will contain all the names of the Columns
of a particular table.
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
for (String column : columnsList.split(",")) {
//check whether rs.getString(column) is a valid JSON String?
if(rs.getString(column).ISvalid_JSON_String()) {
System.out.println("Valid JSON String data")
}
}
}
I am not sure how should I check whether the data I got back for each column is a valid JSON String or not?
Any thoughts?
If you need to be sure it really is valid JSON you're going to need to parse it. A fast, simple, lightweight parser that I like is json-simple. Have a look at their examples here.
Adapting your code I get:
JSONParser parser = new JSONParser();
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
for (String column : columnsList.split(",")) {
//check whether rs.getString(column) is a valid JSON String?
try{
parser.parse(rs.getString(column));
System.out.println("Valid JSON String data");
} catch (ParseException e) {
System.out.printlnn("Invalid JSON String data");
}
}
}