Last active
December 23, 2015 09:20
-
-
Save ridsatrio/917937a15a2059254778 to your computer and use it in GitHub Desktop.
Base class to facilitate JSON-backed entities
This file contains 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
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