Skip to content

Instantly share code, notes, and snippets.

@ridsatrio
Last active December 23, 2015 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ridsatrio/917937a15a2059254778 to your computer and use it in GitHub Desktop.
Save ridsatrio/917937a15a2059254778 to your computer and use it in GitHub Desktop.
Base class to facilitate JSON-backed entities
import org.json.JSONException;
import org.json.JSONObject;
public abstract class JsonBackedObject {
protected final JSONObject source;
JsonBackedObject(String json) {
source = parsedObject(json);
}
protected String valueForKey(String key) throws JSONException {
try {
return source.getString(key);
} catch (JSONException e) {
throw new JSONException("The key \"" + key + "\" was not found in the JSON source");
}
}
@NonNull
private JSONObject parsedObject(String json) {
JSONObject parsedObject;
try {
parsedObject = new JSONObject(json);
} catch (JSONException anException) {
try {
parsedObject = new JSONObject("{}");
} catch (JSONException notPossible) {
throw new AssertionError();
}
}
return parsedObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment