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);
null
) but have to deal with type casting. – Paternalnull
value takes almost no time, testing for value ofString
takes a long time. – Paternal==
andString.equals
will be significant. – BloodmobileJSONObject.optString()
does coerceJSONObject.NULL
to string with value"null"
too. In other words"null".equals(new JSONObject().put("test", JSONObject.NULL).optString("test", null))
givestrue
. – Bracer