1

I have a text json that I recover from an API, but I can not decode it, because in the json I have only one object and not several:

{  
   "address": "[email protected]",
   "username": "mickaelnanah",
   "domain": "gmail.com",
   "md5Hash": "0f6082627bfdeb56a3792f52ce8f0cb8",
   "validFormat": true,
   "deliverable": true,
   "fullInbox": false,
   "hostExists": true,
   "catchAll": false,
   "disposable": false,
   "free": true
}

my code:

val jsonObj = JSONObject(jSonString.substring(jSonString.indexOf("{"), jSonString.lastIndexOf("}") + 1))
val mail = Email(jsonObj.getJSONObject("deliverable") as String)
println(mail.email)

Error:

Exception in thread "main" org.json.JSONException: JSONObject["deliverable"] is not a JSONObject.

I understand the error, it's because I do not have a name to the object, how can I directly take the fields?

SOLVED:

val jsonObj = JSONObject(jSonString.substring(jSonString.indexOf("{"), jSonString.lastIndexOf("}") + 1))

            val mail: String = jsonObj.get("deliverable").toString()

1 Answer 1

2

Since the keys you're using don't refer to nested objects inside your top level JSON object, you should use methods other than getJSONObject to access them.

For example, for the deliverable field, which is a boolean value:

val deliverable: Boolean = jsonObj.getBoolean("deliverable")

Or for the address field, a string:

val address: String = jsonObj.getString("address")

The valid use case for getJSONObject would be when you have a nested object like this:

{
    "nested": {
        "foo": "bar"
    }
}

Here you could do jsonObj.getJSONObject("nested").getString("foo"), for example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.