2

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?

Simson
  • 3,373
  • 2
  • 24
  • 38

2 Answers2

4

You should use optInt (String name, int fallback) to achieve your task.

public int optInt (String name, int fallback)

Returns the value mapped by name if it exists and is an int or can be coerced to an int, or fallback otherwise

Your code will be

val x: Int = j.optInt("mykey", 0)
Simson
  • 3,373
  • 2
  • 24
  • 38
Son Truong
  • 13,661
  • 5
  • 32
  • 58
3

You can use is just like instanceof in java -

if (j.has("mykey"){
    val myValue = j["mykey"]
    if(myValue is Int){
        //Use myValue here
    }
}
Naresh NK
  • 1,036
  • 1
  • 9
  • 16