Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.getString doesn't return null

Tags:

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

like image 696
thepoosh Avatar asked Oct 29 '12 08:10

thepoosh


People also ask

How do you check if a JSON object is null?

To check null in JavaScript, use triple equals operator(===) or Object is() method. If you want to use Object.is() method then you two arguments. 1) Pass your variable value with a null value. 2) The null value itself.

Can JsonArray be null?

An INTEGER variable that represents the size of the new JsonArray. Each element is initialized to the JSON null value. If this value is 0, the array is empty.

How check JSON object is null or not in android?

Try with json. isNull( "field-name" ) . I would go further and say to NEVER use has(KEY_NAME), replacing those calls to ! isNull(KEY_NAME).


1 Answers

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.

like image 106
Sujay Avatar answered Sep 19 '22 03:09

Sujay