diff --git a/gson/src/main/java/com/google/gson/JsonObject.java b/gson/src/main/java/com/google/gson/JsonObject.java index 2901a8ce..1775ede8 100644 --- a/gson/src/main/java/com/google/gson/JsonObject.java +++ b/gson/src/main/java/com/google/gson/JsonObject.java @@ -54,6 +54,16 @@ public final class JsonObject extends JsonElement { members.put(property, value); } + /** + * Removes the {@code property} from this {@link JsonObject}. + * + * @param property name of the member that should be removed. + * return the {@link JsonElement} object that is being removed. + */ + public JsonElement remove(String property) { + return members.remove(property); + } + /** * Convenience method to add a primitive member. The specified value is converted to a * JsonPrimitive of String. diff --git a/gson/src/test/java/com/google/gson/JsonObjectTest.java b/gson/src/test/java/com/google/gson/JsonObjectTest.java new file mode 100644 index 00000000..5744653b --- /dev/null +++ b/gson/src/test/java/com/google/gson/JsonObjectTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2008 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gson; + +import junit.framework.TestCase; + +/** + * Unit test for the {@link JsonObject} class. + * + * @author Joel Leitch + */ +public class JsonObjectTest extends TestCase { + + public void testAddingAndRemovingObjectProperties() throws Exception { + JsonObject jsonObj = new JsonObject(); + String propertyName = "property"; + assertFalse(jsonObj.has(propertyName)); + assertNull(jsonObj.get(propertyName)); + + JsonPrimitive value = new JsonPrimitive("blah"); + jsonObj.add(propertyName, value); + assertEquals(value, jsonObj.get(propertyName)); + + JsonElement removedElement = jsonObj.remove(propertyName); + assertEquals(value, removedElement); + assertFalse(jsonObj.has(propertyName)); + } + + public void testAddingNullProperties() throws Exception { + String propertyName = "property"; + JsonObject jsonObj = new JsonObject(); + jsonObj.add(propertyName, null); + + assertTrue(jsonObj.has(propertyName)); + + JsonElement jsonElement = jsonObj.get(propertyName); + assertNotNull(jsonElement); + assertTrue(jsonElement.isJsonNull()); + } +}