While writing up a unit test for a service I had written, I needed to parse out a JSON test string into a large JSON object. I found the best way to do this was to place the test data in a file located in the 'res/raw' folder (create this folder if your project does not include it already) and then read the file, and parse it as a JSON object.
private JSONObject createJSONFromFile(int fileID) {
JSONObject result = null;
try {
// Read file into string builder
InputStream inputStream = mTestContext.getResources().openRawResource(fileID);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null ; ) {
builder.append(line).append("\n");
}
// Parse into JSONObject
String resultStr = builder.toString();
JSONTokener tokener = new JSONTokener(resultStr);
result = new JSONObject(tokener);
}
catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
private void loadTestFile() {
JSONObject test = createJSONFromFile(R.raw.testdata_valid);
// ... do awesome stuff with test data ...
}
by Shayla Sawchenko