Browse Source

Fix Issue #497 and add a testcase (#699)

* The method getPropertyKeys() in class JsonOrgJsonProvider doesn't check empty jsonObject.

* Addition testcase

* simplify the implementation. And change method names of testcases to something more descriptive

* change names
pull/732/head
Pigdrum 3 years ago committed by GitHub
parent
commit
7384e960c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 12
      json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonOrgJsonProvider.java
  2. 21
      json-path/src/test/java/com/jayway/jsonpath/JsonOrgJsonProviderTest.java

12
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<String> getPropertyKeys(Object obj) {
JSONObject jsonObject = toJsonObject(obj);
List<String> keys = new ArrayList<String>();
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);
}

21
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\"]");
}
}

Loading…
Cancel
Save