From 49b72a102d3dc1d0ffab666ea33abdcb42faaea4 Mon Sep 17 00:00:00 2001 From: Pascal Bihler Date: Thu, 16 Nov 2017 12:14:57 +0100 Subject: [PATCH] Added JsonObject.getObject(String) method to complete helper API --- .../java/com/eclipsesource/json/JsonObject.java | 17 +++++++++++++++++ .../com/eclipsesource/json/JsonObject_Test.java | 16 ++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/com.eclipsesource.json/src/main/java/com/eclipsesource/json/JsonObject.java b/com.eclipsesource.json/src/main/java/com/eclipsesource/json/JsonObject.java index 12ece65..3530a4d 100644 --- a/com.eclipsesource.json/src/main/java/com/eclipsesource/json/JsonObject.java +++ b/com.eclipsesource.json/src/main/java/com/eclipsesource/json/JsonObject.java @@ -561,6 +561,23 @@ public JsonValue get(String name) { return index != -1 ? values.get(index) : null; } + /** + * Returns the JsonObject value of the member with the specified name in this object. If + * this object does not contain a member with this name, null is returned. If + * this object contains multiple members with the given name, the last one will be picked. If this + * member's value does not represent a JSON number or if it cannot be interpreted as Java + * int, an exception is thrown. + * + * @param name + * the name of the member whose value is to be returned + * @return the value of the last member with the specified name, or the given default value if + * this object does not contain a member with that name + */ + public JsonObject getObject(String name) { + JsonValue value = get(name); + return value != null ? value.asObject() : null; + } + /** * Returns the int value of the member with the specified name in this object. If * this object does not contain a member with this name, the given default value is returned. If diff --git a/com.eclipsesource.json/src/test/java/com/eclipsesource/json/JsonObject_Test.java b/com.eclipsesource.json/src/test/java/com/eclipsesource/json/JsonObject_Test.java index 5c72d1b..f6ce9fd 100644 --- a/com.eclipsesource.json/src/test/java/com/eclipsesource/json/JsonObject_Test.java +++ b/com.eclipsesource.json/src/test/java/com/eclipsesource/json/JsonObject_Test.java @@ -298,6 +298,22 @@ public void get_returnsLastValueForName() { assertEquals(Json.TRUE, object.get("foo")); } + @Test + public void get_object_returnsValueFromMember() { + JsonObject member = new JsonObject(); + member.add("foo", "bar"); + + object.add("foo", member); + + assertEquals("bar", object.getObject("foo").getString("foo",null)); + } + + @Test + public void get_object_returnsNullForMissingMember() { + assertNull(object.getObject("foo")); + } + + @Test public void get_int_returnsValueFromMember() { object.add("foo", 23);