I want to check if an entry in my JSONObject
exists and is the type it should be to avoid an exception when used.
I found my question almost has an answer for Java Check if JSONObject key exists to use the has()
operator
import org.json.JSONArray
import org.json.JSONObject
var j:JSONObject
...
val x:Int = if (j.has("mykey"){
j["mykey"] as Int
}else {
0
}
If val x:Int = j["mykey"] as Int
is executed without the check it will throw an exception.
Is there a more kotlinish way, maybe with some Elvis operator or something, of doing this check?
What is good way to get get the type of j["mykey"]
without risking triggering an exception?