Skip to content

Instantly share code, notes, and snippets.

@rubdottocom
Created June 13, 2018 13:49
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 rubdottocom/bdfd6525d7ad1dd7d0064d5b5b22c949 to your computer and use it in GitHub Desktop.
Save rubdottocom/bdfd6525d7ad1dd7d0064d5b5b22c949 to your computer and use it in GitHub Desktop.
Extension functions to work more comfortably with JSONObject. The idea is to capture nulls instead of Exception or bother with .has function
// WARNING, this code doesn't work, is an example of usage
val json = JSONObject()
json.safeGetString("property")?.let {
// Do awesome things with property value
}
private fun JSONObject.safeGetJSONArray(element: String) : JSONArray? {
return if (this.has(element))
this.getJSONArray(element)
else
null
}
private fun JSONObject.safeGetJSONObject(element: String) : JSONObject? {
return if (this.has(element))
this.getJSONObject(element)
else
null
}
private fun JSONObject.safeGetString(element: String) : String? {
return if (this.has(element))
this.getString(element)
else
null
}
private fun JSONObject.safeGetInt(element: String) : Int? {
return if (this.has(element))
this.getInt(element)
else
null
}
private fun JSONObject.safeGetBoolean(element: String) : Boolean? {
return if (this.has(element))
this.getBoolean(element)
else
null
}
private fun JSONObject.safeGetDouble(element: String) : Double? {
return if (this.has(element))
this.getDouble(element)
else
null
}
private fun JSONObject.getJSONObjectFromJSONArrayIndex(element: String, index: Int) : JSONObject? {
return try {
JSONObject(this.getJSONArray(element)[index].toString())
} catch (e:Exception) {
null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment