Search code examples
javajsonstringresultset

Check whether the String is a Valid JSON String or not?


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?


Solution

  • 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.

    http://code.google.com/p/json-simple/wiki/DecodingExamples#Example_2_-_Faster_way:_Reuse_instance_of_JSONParser

    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");
            }
        }
    }