Skip to content

Commit 14953da

Browse files
authored
Merge pull request json-path#368 from jochenberger/fix-gson-mapping-null
`null` should be mapped to `null` (fixes json-path#351)
2 parents 96bff2d + 78befbb commit 14953da

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

json-path/src/main/java/com/jayway/jsonpath/spi/mapper/GsonMappingProvider.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,9 @@ public Gson call() {
6262

6363
@Override
6464
public <T> T map(Object source, Class<T> targetType, Configuration configuration) {
65+
if(source == null){
66+
return null;
67+
}
6568
try {
6669
return factory.call().getAdapter(targetType).fromJsonTree((JsonElement) source);
6770
} catch (Exception e){
@@ -71,6 +74,9 @@ public <T> T map(Object source, Class<T> targetType, Configuration configuration
7174

7275
@Override
7376
public <T> T map(Object source, TypeRef<T> targetType, Configuration configuration) {
77+
if(source == null){
78+
return null;
79+
}
7480
try {
7581
return (T) factory.call().getAdapter(TypeToken.get(targetType.getType())).fromJsonTree((JsonElement) source);
7682
} catch (Exception e){

json-path/src/test/java/com/jayway/jsonpath/GsonJsonProviderTest.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import com.google.gson.JsonArray;
44
import com.google.gson.JsonElement;
55
import com.google.gson.JsonObject;
6+
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
7+
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
68
import com.jayway.jsonpath.spi.mapper.MappingException;
79
import org.junit.Test;
810

@@ -181,6 +183,25 @@ public void test_type_ref_fail() throws IOException {
181183

182184
using(GSON_CONFIGURATION).parse(JSON).read("$", typeRef);
183185
}
186+
187+
@Test
188+
// https://github.com/json-path/JsonPath/issues/351
189+
public void no_error_when_mapping_null() throws IOException {
190+
191+
Configuration configuration = Configuration
192+
.builder()
193+
.mappingProvider(new GsonMappingProvider())
194+
.jsonProvider(new GsonJsonProvider())
195+
.options(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.SUPPRESS_EXCEPTIONS)
196+
.build();
197+
198+
String json = "{\"M\":[]}";
199+
200+
String result = JsonPath.using(configuration).parse(json).read("$.M[0].A[0]", String.class);
201+
202+
assertThat(result).isNull();
203+
}
204+
184205

185206
public static class FooBarBaz<T> {
186207
public T gen;

0 commit comments

Comments
 (0)