Created
June 13, 2018 13:49
-
-
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
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
// WARNING, this code doesn't work, is an example of usage | |
val json = JSONObject() | |
json.safeGetString("property")?.let { | |
// Do awesome things with property value | |
} |
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
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