Uploaded image for project: 'Sling'
  1. Sling
  2. SLING-929

JSONObject.append() fails when adding second value

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • Commons JSON 2.0.2
    • Commons JSON 2.0.4
    • None
    • None

    Description

      o.a.s.c.json.JSONObject#append has an ugly typo in it.

      The method is supposed, according to the javadoc, to create an array when the first value is added, and then append to the array on subsequent values.

      So that this test should pass:
      1: JSONObject obj = new JSONObject();
      2: obj.append("key", "value1");
      3: obj.append("key", "value2");
      4: Object result = obj.get("key");
      5: assertTrue("Did not create an array", result instanceof JSONArray);

      However, an exception is thrown at line #3:
      org.apache.sling.commons.json.JSONException: JSONObject[key] is not a JSONArray.
      at org.apache.sling.commons.json.JSONObject.append(JSONObject.java:327)

      There's an if-else block in append() that checks if the array already exists. If there's already a property with the same key, which is not an array, the exception should be thrown. However, instead an exception is thrown when an array already exists.

      This code seems to have been copied from JSON.org. The original code (view-source:http://www.json.org/java/org/json/JSONObject.java) has the if-else block reversed.

      Coming up with a patch and a testcase.

      Attachments

        Activity

          People

            vramdal Vidar Skauge Ramdal
            vramdal Vidar Skauge Ramdal
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: