slashnick
slashnick

Reputation: 26549

Is it possible to get null from getString using JSONLib

I'm using JSON-lib to parse an object and read a string from it. This works fine for a valid string but it can also be null. For example:

JSONObject jsonObject = JSONObject.fromObject("{\"foo\":null}");
String str = jsonObject.getString("foo");

In this case I would expect str to be null but it is instead "null". Calling any other method seems to throw an error. Is there anyway to have JSONLib parse a string if the value is a string but return null if the value is null?

Upvotes: 2

Views: 3821

Answers (4)

Ronit Pradhan
Ronit Pradhan

Reputation: 1

Why not make use of JSONObject::opt? You'll get a null (not "null") if the key doesn't exist.

String str = (String) jsonObject.opt("foo");

Upvotes: 0

www.thuvien247.net
www.thuvien247.net

Reputation: 31

It's a bug of JSONLib which has been reported .

https://github.com/douglascrockford/JSON-java/issues/5

Upgrading your jsonlib to latest version will probably fix it.

Upvotes: 1

slashnick
slashnick

Reputation: 26549

I couldn't find a nice way to do this, so I did switch to Jackson instead. This allows me to do:

JsonNode json = (new ObjectMapper()).readValue("{\"foo\":null}", JsonNode.class);
json.get("stopType").getTextValue();

Which will return null for this example, as expected.

Upvotes: 1

lukastymo
lukastymo

Reputation: 26809

JSONObject.java:

/**
* Get the string associated with a key.
*
* @param key A key string.
* @return A string which is the value.
* @throws JSONException if the key is not found.
*/
public String getString( String key ) {
    verifyIsNull();
    Object o = get( key );
    if( o != null ){
        return o.toString();
    }
    throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] not found." );
}

You can see that getString() never return null. It can return "null" if o.toString() do that but this will be String not null value

Upvotes: 3

Related Questions