diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index d6f76a48a..c1d797699 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -177,10 +177,14 @@ public JSONObject() { * @param jo * A JSONObject. * @param names - * An array of strings. + * An array of strings. A null array selects no keys and creates + * an empty JSONObject. */ public JSONObject(JSONObject jo, String ... names) { - this(names.length); + this(names == null ? 0 : names.length); + if (names == null) { + return; + } for (int i = 0; i < names.length; i += 1) { try { this.putOnce(names[i], jo.opt(names[i])); @@ -510,10 +514,14 @@ private JSONObject(Object bean, Set objectsRecord) { * JSONObject. * @param names * An array of strings, the names of the fields to be obtained - * from the object. + * from the object. A null array selects no fields and creates + * an empty JSONObject. */ public JSONObject(Object object, String ... names) { - this(names.length); + this(names == null ? 0 : names.length); + if (names == null) { + return; + } Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { String name = names[i]; diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index ecc3204e7..f5433b0d3 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -285,6 +285,27 @@ public void jsonObjectByNames() { Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList(jsonObject, jsonObjectByName))); } + @Test + public void jsonObjectByNullNames() { + JSONObject source = new JSONObject().put("value", 1); + JSONObject subset = new JSONObject(source, (String[]) null); + assertTrue("null names should select no keys", subset.isEmpty()); + assertEquals("source should be unchanged", 1, source.getInt("value")); + } + + @Test + public void jsonObjectByObjectAndNullNames() { + JSONObject subset = new JSONObject(new MyPublicClass(), (String[]) null); + assertTrue("null names should select no fields", subset.isEmpty()); + } + + @Test + public void jsonObjectByNamesFromEmptyObject() { + JSONObject source = new JSONObject(); + JSONObject subset = new JSONObject(source, JSONObject.getNames(source)); + assertTrue("names from an empty object should select no keys", subset.isEmpty()); + } + /** * JSONObjects can be built from a Map. In this test the map is * null. the JSONObject(JsonTokener) ctor is not tested directly since it