Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/main/java/org/json/JSONObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -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]));
Expand Down Expand Up @@ -510,10 +514,14 @@ private JSONObject(Object bean, Set<Object> 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];
Expand Down
21 changes: 21 additions & 0 deletions src/test/java/org/json/junit/JSONObjectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,27 @@ public void jsonObjectByNames() {
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(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<String, Object>. In this test the map is
* null. the JSONObject(JsonTokener) ctor is not tested directly since it
Expand Down
Loading