JSON.getString doesn't return null

The hack looks okay for your situation.

The other option would be to use the method boolean isNull(String key) and then based on the returned boolean value proceed with your option. Something like:

public String getMessageFromServer(JSONObject response) {
    return ((response.has("message") && !response.isNull("message"))) ? response.getString("message") : null;
} 

But then, I don't think there's much of a difference between the your current implementation and this.


This is easy to solve when using Kotlin class extensions:

fun JSONObject.optNullableString(name: String, fallback: String? = null) : String? {
    return if (this.has(name) && !this.isNull(name)) {
        this.getString(name)
    } else {
        fallback
    }
}

Then e.g. name will be null in:

val name : String? = JSONObject("""{"id": "foo", "name":null}""").optNullableString("name")