Created
June 16, 2015 10:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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