Loading ...
Sorry, an error occurred while loading the content.

Possible bugs in java library (org.json) ?

Expand Messages
  • Viktor Bresan
    Hi to all. I ve detected some awkward behavior in org.json library and the best would be that someone convinces me that I am missing something obvious. :-) 1)
    Message 1 of 1 , Feb 26 5:12 PM
    • 0 Attachment
      Hi to all.

      I've detected some awkward behavior in org.json library and
      the best would be that someone convinces me that I am
      missing something obvious. :-)


      1) Observe the following:

      String[] strings = new String[] { "null", null, "something else" };

      JSONArray jsonArray = new JSONArray();
      jsonArray.put(strings[0]);
      jsonArray.put(strings[1]);
      jsonArray.put(strings[2]);

      Object o1 = jsonArray.get(0);
      Object o2 = jsonArray.get(1); ///!!!
      Object o3 = jsonArray.get(2);


      jsonArray.get(1) throws the following exception:

      Exception in thread "main" org.json.JSONException: JSONArray[1] not found.
      at org.json.JSONArray.get(JSONArray.java:204)

      In my opinion, this is wrong and exception should not be thrown.
      null values are valid elements of JSON arrays and get statement should return it.

      Mind that the same exception is thrown in this case and in case I call for example
      jsonArray.get(1000) // some index out of array bounds

      However, the later statement should throw exception.


      2) let's say we continue with the previous example:

      String asString = jsonArray.toString(); // ["null",null,"something else"]
      System.out.println("JSONArray as string: " + asString);

      JSONArray jsonArray2 = new JSONArray(asString);

      if (jsonArray2.getString(0) != null) {
      System.out.println("jsonArray2.getString(0): " + jsonArray2.getString(0));
      } else {
      System.out.println("jsonArray2.getString(0) is NULL!");
      }

      if (jsonArray2.getString(1) != null) {
      System.out.println("jsonArray2.getString(1): " + jsonArray2.getString(1));
      } else {
      System.out.println("jsonArray2.getString(1) is NULL!");
      }



      The output is the following:

      JSONArray as string: ["null",null,"something else"]
      jsonArray2.getString(0): null
      jsonArray2.getString(1): null


      In human language - have provided legal json string to JSONArray construcor, namely:
      ["null",null,"something else"]

      I fetch the first value, string "null" and since it obviously is not null, it's printed on sysout.
      I fetch the second value, but instead of getting null String i get back string "null" as well.

      It seems that "null" and null, which are different in JSON both get parsed as string "null".

      Am I missing something here?
    Your message has been successfully submitted and would be delivered to recipients shortly.