DATACMNS-1145 - @JsonPath value lookup now returns null for non-existent paths.

If a JSONPath expression is using a path not available in the backing payload we now return null rather than letting the PathNotFoundException propagate.
This commit is contained in:
Oliver Gierke
2017-08-24 15:45:55 +02:00
parent 3ffb18597b
commit 2bfd278861
2 changed files with 29 additions and 16 deletions

View File

@@ -42,6 +42,7 @@ import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.ParseContext;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.TypeRef;
import com.jayway.jsonpath.spi.mapper.MappingProvider;
@@ -135,24 +136,31 @@ public class JsonProjectingMethodInterceptorFactory implements MethodInterceptor
ResolvableType type = ResolvableType.forMethodReturnType(method);
String jsonPath = getJsonPath(method);
if (returnType.getActualType().getType().isInterface()) {
try {
List<?> result = context.read(jsonPath);
return result.isEmpty() ? null : result.get(0);
if (returnType.getActualType().getType().isInterface()) {
List<?> result = context.read(jsonPath);
return result.isEmpty() ? null : result.get(0);
}
boolean isCollectionResult = Collection.class.isAssignableFrom(type.getRawClass());
type = isCollectionResult ? type : ResolvableType.forClassWithGenerics(List.class, type);
type = isCollectionResult && JsonPath.isPathDefinite(jsonPath)
? ResolvableType.forClassWithGenerics(List.class, type)
: type;
List<?> result = (List<?>) context.read(jsonPath, new ResolvableTypeRef(type));
if (isCollectionResult && JsonPath.isPathDefinite(jsonPath)) {
result = (List<?>) result.get(0);
}
return isCollectionResult ? result : result.isEmpty() ? null : result.get(0);
} catch (PathNotFoundException o_O) {
return null;
}
boolean isCollectionResult = Collection.class.isAssignableFrom(type.getRawClass());
type = isCollectionResult ? type : ResolvableType.forClassWithGenerics(List.class, type);
type = isCollectionResult && JsonPath.isPathDefinite(jsonPath)
? ResolvableType.forClassWithGenerics(List.class, type) : type;
List<?> result = (List<?>) context.read(jsonPath, new ResolvableTypeRef(type));
if (isCollectionResult && JsonPath.isPathDefinite(jsonPath)) {
result = (List<?>) result.get(0);
}
return isCollectionResult ? result : result.isEmpty() ? null : result.get(0);
}
/**

View File

@@ -137,6 +137,11 @@ public class JsonProjectingMethodInterceptorFactoryUnitTests {
assertThat(customer.getNestedCities(), hasSize(2));
}
@Test // DATACMNS-1144
public void returnsNullForNonExistantValue() {
assertThat(customer.getName().getLastname(), is(nullValue()));
}
interface Customer {
String getFirstname();