2

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?

7
  • Is that the real source code? The "argument" to the fromObject call doesn't look like valid Java. Commented Apr 8, 2011 at 12:39
  • quite right, I'll update Commented Apr 8, 2011 at 12:55
  • 1
    JSONLib is crap. Use GSON or Jackson instead. Commented Apr 8, 2011 at 12:59
  • So you called .getString(), which returns a String, and you expected something other than a string? Commented Apr 8, 2011 at 12:59
  • @jsumners Why is it so absurd to you that .getString() could return NULL? String extends Object, right, and Objects can be equal to NULL? Or am I missing something? Commented Mar 28, 2012 at 11:24

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.