Extracting JSON data into Java objects
Now that the basic syntax has been covered, we will start building the JSON DataProvider method. First, we need a file I/O method to read the JSON data from a file. The parameter to the method will be the filename, including the path and string type. The method will be static and return JSONObject
. Here is the code sample:
/** * extractData_JSON - method to extract JSON data from a file * * @param file (including path) * @return JSONObject * @throws Exception */ public static JSONObject extractData_JSON(String file) throws Exception { FileReader reader = new FileReader(file); JSONParser jsonParser = new JSONParser(); return (JSONObject) jsonParser.parse(reader); }
In cases where users might want to extract only specific sets of JSON data, as when filtering for specific test cases, they could create a wrapper method around the extractData_JSON
method that would allow a parameter to be used as a filter. This method would also be static...