From 78befbb5ee80fb8e403f76375c8d693c60ba46e0 Mon Sep 17 00:00:00 2001 From: Jochen Berger Date: Thu, 29 Jun 2017 12:48:13 +0200 Subject: [PATCH] `null` should be mapped to `null` (fixes #351) --- .../spi/mapper/GsonMappingProvider.java | 6 ++++++ .../jayway/jsonpath/GsonJsonProviderTest.java | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/json-path/src/main/java/com/jayway/jsonpath/spi/mapper/GsonMappingProvider.java b/json-path/src/main/java/com/jayway/jsonpath/spi/mapper/GsonMappingProvider.java index 7e5153b4..2b5ead3c 100644 --- a/json-path/src/main/java/com/jayway/jsonpath/spi/mapper/GsonMappingProvider.java +++ b/json-path/src/main/java/com/jayway/jsonpath/spi/mapper/GsonMappingProvider.java @@ -62,6 +62,9 @@ public class GsonMappingProvider implements MappingProvider { @Override public T map(Object source, Class targetType, Configuration configuration) { + if(source == null){ + return null; + } try { return factory.call().getAdapter(targetType).fromJsonTree((JsonElement) source); } catch (Exception e){ @@ -71,6 +74,9 @@ public class GsonMappingProvider implements MappingProvider { @Override public T map(Object source, TypeRef targetType, Configuration configuration) { + if(source == null){ + return null; + } try { return (T) factory.call().getAdapter(TypeToken.get(targetType.getType())).fromJsonTree((JsonElement) source); } catch (Exception e){ diff --git a/json-path/src/test/java/com/jayway/jsonpath/GsonJsonProviderTest.java b/json-path/src/test/java/com/jayway/jsonpath/GsonJsonProviderTest.java index 1fc85bd9..5cca22b4 100644 --- a/json-path/src/test/java/com/jayway/jsonpath/GsonJsonProviderTest.java +++ b/json-path/src/test/java/com/jayway/jsonpath/GsonJsonProviderTest.java @@ -3,6 +3,8 @@ package com.jayway.jsonpath; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.jayway.jsonpath.spi.json.GsonJsonProvider; +import com.jayway.jsonpath.spi.mapper.GsonMappingProvider; import com.jayway.jsonpath.spi.mapper.MappingException; import org.junit.Test; @@ -181,6 +183,25 @@ public class GsonJsonProviderTest extends BaseTest { using(GSON_CONFIGURATION).parse(JSON).read("$", typeRef); } + + @Test + // https://github.com/json-path/JsonPath/issues/351 + public void no_error_when_mapping_null() throws IOException { + + Configuration configuration = Configuration + .builder() + .mappingProvider(new GsonMappingProvider()) + .jsonProvider(new GsonJsonProvider()) + .options(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.SUPPRESS_EXCEPTIONS) + .build(); + + String json = "{\"M\":[]}"; + + String result = JsonPath.using(configuration).parse(json).read("$.M[0].A[0]", String.class); + + assertThat(result).isNull(); + } + public static class FooBarBaz { public T gen;