Skip to content

Instantly share code, notes, and snippets.

@dominicthomas
Created June 16, 2015 10:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dominicthomas/ec1ce6d98dc81f6db614 to your computer and use it in GitHub Desktop.
Save dominicthomas/ec1ce6d98dc81f6db614 to your computer and use it in GitHub Desktop.
Open a json file from the android raw directory and construct using GSON.
public class JSONUtils {
/**
* Open a json file from raw and construct as class using Gson.
*
* @param resources
* @param resId
* @param classType
* @param <T>
* @return
*/
public static <T> Optional<T> getJsonFileAsClass(final Resources resources, final int resId, final Class<T> classType) {
InputStream resourceReader = resources.openRawResource(resId);
Writer writer = new StringWriter();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceReader, "UTF-8"));
String line = reader.readLine();
while (line != null) {
writer.write(line);
line = reader.readLine();
}
return Optional.of(constructUsingGson(classType, writer.toString()));
} catch (Exception e) {
Crashlytics.logException(e);
Timber.d("Unhandled exception while using JSONResourceReader", e);
} finally {
try {
resourceReader.close();
} catch (Exception e) {
Timber.d("Unhandled exception while using JSONResourceReader", e);
}
}
return Optional.absent();
}
/**
* Build an object from the specified JSON resource using Gson.
*
* @param type The type of the object to build.
* @return An object of type T, with member fields populated using Gson.
*/
private static <T> T constructUsingGson(final Class<T> type, final String jsonString) {
Gson gson = new GsonBuilder().create();
return gson.fromJson(jsonString, type);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment