Search code examples
javajsonjson-lib

Can't parse JSON property "null"


I faced with one trouble when tried to parse JSON "null" property, please help me to understand what's the real problem. I had a following JSON:

{
  "properties" : {        
    "null" : {
      "value" : false
    }
  }
}

I used http://jsonlint.com to validate that this JSON is valid. I tried to parse it from java:

import net.sf.json.JSONObject;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        String st = "{" +
                "      'properties' : {" +
                "        'null' : {" +
                "          'value' : false" +
                "        }" +
                "      }" +
                "}";
        JSONObject.fromObject(st);
    }
}

But got the exception:

Exception in thread "main" java.lang.ClassCastException: JSON keys must be strings.
    at net.sf.json.JSONObject._fromJSONObject(JSONObject.java:927)
    at net.sf.json.JSONObject.fromObject(JSONObject.java:155)
    at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:108)
    at net.sf.json.AbstractJSON._processValue(AbstractJSON.java:238)
    at net.sf.json.JSONObject._processValue(JSONObject.java:2655)
    at net.sf.json.JSONObject.processValue(JSONObject.java:2721)
    at net.sf.json.JSONObject.element(JSONObject.java:1786)
    at net.sf.json.JSONObject._fromJSONTokener(JSONObject.java:1036)
    at net.sf.json.JSONObject._fromString(JSONObject.java:1201)
    at net.sf.json.JSONObject.fromObject(JSONObject.java:165)
    at net.sf.json.JSONObject.fromObject(JSONObject.java:134)

I used json-lib-2.4-jdk15.jar from http://json-lib.sourceforge.net to parse it. Could anybody please clarify this? Why this library throws exception, but online validator said that it's valid JSON? It is a bug in the library or I made something wrong?


Solution

  • The first JSON posted is valid JSON: the JSON in the Java, however, is not valid -- only " is valid for the [required] key quote. From json.org:

    A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes....

    However, that sounds like a bug, assuming it was not triggered by the invalid JSON fed to it (the library can do whatever it wants with invalid JSON)... one would have to look at the source (or bug reports / user experience) to say conclusively if this is indeed a "bug". I have added some suggestions of things to try below which may either show expected behavior or outline the cause/issue in further detail.

    Consider this minimal test-case (with valid JSON):

    String st = "{ \"null\": \"hello world!\" }";
    

    This may also shed more light, depending on if the first item is "null" or null when extracted:

    String st = "[ \"null\" ]";
    

    Happy coding.