diff --git a/json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonOrgJsonProvider.java b/json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonOrgJsonProvider.java index 8dc22bb5..773d82a5 100644 --- a/json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonOrgJsonProvider.java +++ b/json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonOrgJsonProvider.java @@ -14,6 +14,7 @@ import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Objects; public class JsonOrgJsonProvider extends AbstractJsonProvider { @@ -143,17 +144,14 @@ public class JsonOrgJsonProvider extends AbstractJsonProvider { return (obj instanceof JSONObject); } + @SuppressWarnings("unchecked") @Override public Collection getPropertyKeys(Object obj) { JSONObject jsonObject = toJsonObject(obj); - List keys = new ArrayList(); try { - for (int i = 0; i < jsonObject.names().length(); i++) { - String key = (String) jsonObject.names().get(i); - keys.add(key); - - } - return keys; + if(Objects.isNull(jsonObject.names())) + return new ArrayList<>(); + return jsonObject.keySet(); } catch (JSONException e) { throw new JsonPathException(e); } diff --git a/json-path/src/test/java/com/jayway/jsonpath/JsonOrgJsonProviderTest.java b/json-path/src/test/java/com/jayway/jsonpath/JsonOrgJsonProviderTest.java index 47ce0c1e..8600de88 100644 --- a/json-path/src/test/java/com/jayway/jsonpath/JsonOrgJsonProviderTest.java +++ b/json-path/src/test/java/com/jayway/jsonpath/JsonOrgJsonProviderTest.java @@ -1,5 +1,7 @@ package com.jayway.jsonpath; +import com.jayway.jsonpath.spi.json.JsonOrgJsonProvider; +import com.jayway.jsonpath.spi.mapper.JsonOrgMappingProvider; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Test; @@ -76,4 +78,23 @@ public class JsonOrgJsonProviderTest extends BaseTest { assertThat(result).isEqualTo(4); } + @Test + public void test_getPropertyKeys_empty_object() { + String json = "{\"foo\": \"bar\", \"emptyObject\": {},\"emptyList\":[]}"; + Configuration config = Configuration.defaultConfiguration() + .jsonProvider(new JsonOrgJsonProvider()) + .mappingProvider(new JsonOrgMappingProvider()); + Object result = JsonPath.using(config).parse(json).read("$..foo"); + assertThat(result.toString()).isEqualTo("[\"bar\"]"); + } + + @Test + public void test_getPropertyKeys_empty_nest_object() { + String json = "{\"foo\": \"bar\", \"emptyObject\": {\"emptyList\":[]},\"emptyList\":[]}"; + Configuration config = Configuration.defaultConfiguration() + .jsonProvider(new JsonOrgJsonProvider()) + .mappingProvider(new JsonOrgMappingProvider()); + Object result = JsonPath.using(config).parse(json).read("$..foo"); + assertThat(result.toString()).isEqualTo("[\"bar\"]"); + } }