thepoosh
thepoosh

Reputation: 12587

JSON.getString doesn't return null

I have a response coming back from a server and I am expecting a String value, so I wrote this for parsing it

public String getMessageFromServer(JSONObject response) {
    String msg = response.getString("message");
    return msg;
}

then, when I use this in my code and get a null value from the server, the function doesn't return null, it returns "null" instead.

I have seen this bug report, but I don't see a solution.

EDIT:

I have a small hack to solve this but it's ugly and I'm looking for a better solution:

public String getMessageFromServer(JSONObject response) {
    Object msg = response.get("message");
    if(msg == null) {
         return null;
    }
    return (String) msg;
}    

EDIT #2:

after years, going back to this question, I see that I was not entirely wrong here and that JSONObject has a built in method for this.

The way to get an optional value from a JSONObject is with using this method JSONObject.optString("message", DEF_VALUE);

Upvotes: 28

Views: 25991

Answers (4)

Prilaga
Prilaga

Reputation: 857

In android sdk default value in optString method is annotated as @NonNull. Just skip it and simplify to get value or null:

fun JSONObject.optStringOrNull(key: String, fallback: String? = null): String? {
    val obj: Any? = opt(key)
    if (obj is String) {
        return obj
    } else if (obj != null) {
        return obj.toString()
    }
    return fallback
}

Upvotes: 0

Vlad
Vlad

Reputation: 8572

More simple way in Kotlin

fun JSONObject.getNullableString(name: String) : String? {
    if (has(name) && !isNull(name)) {
        return getString(name)
    }
    return null
}

Upvotes: 0

jhavatar
jhavatar

Reputation: 3246

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")

Upvotes: 3

Sujay
Sujay

Reputation: 6783

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.

Upvotes: 28

Related Questions