OSDN Git Service

Test and document our handling of nulls with getString().
authorJesse Wilson <jessewilson@google.com>
Thu, 25 Mar 2010 20:31:43 +0000 (13:31 -0700)
committerJesse Wilson <jessewilson@google.com>
Thu, 25 Mar 2010 21:35:00 +0000 (14:35 -0700)
Our behaviour is consistent with Crockford's.

The test confirms that the behaviour is consistent with the report
of that bug, which the submitter claims is not how it should behave.
http://code.google.com/p/android/issues/detail?id=7257

Change-Id: Ibace4bd995e3cbc8fb6c9dc509f8f4491865a647

libcore/json/src/main/java/org/json/JSONObject.java
libcore/json/src/test/java/org/json/JSONArrayTest.java

index 06f7f50..56c91cf 100644 (file)
@@ -48,7 +48,9 @@ import java.util.Map;
  *       large values. For example, the string "9223372036854775806" yields the
  *       long 9223372036854775807.
  *   <li>When the requested type is a String, other non-null values will be
- *       coerced using {@link String#valueOf(Object)}.
+ *       coerced using {@link String#valueOf(Object)}. Although null cannot be
+ *       coerced, the sentinel value {@link JSONObject#NULL} is coerced to the
+ *       string "null".
  * </ul>
  *
  * <p>This class can look up both mandatory and optional values:
index 485a729..09990b9 100644 (file)
@@ -160,6 +160,29 @@ public class JSONArrayTest extends TestCase {
         assertEquals("", array.optString(3));
     }
 
+    /**
+     * Our behaviour is questioned by this bug:
+     * http://code.google.com/p/android/issues/detail?id=7257
+     */
+    public void testParseNullYieldsJSONObjectNull() throws JSONException {
+        JSONArray array = new JSONArray("[\"null\",null]");
+        array.put(null);
+        assertEquals("null", array.get(0));
+        assertEquals(JSONObject.NULL, array.get(1));
+        try {
+            array.get(2);
+            fail();
+        } catch (JSONException e) {
+        }
+        assertEquals("null", array.getString(0));
+        assertEquals("null", array.getString(1));
+        try {
+            array.getString(2);
+            fail();
+        } catch (JSONException e) {
+        }
+    }
+
     public void testNumbers() throws JSONException {
         JSONArray array = new JSONArray();
         array.put(Double.MIN_VALUE);