Skip to content

Commit

Permalink
handle indefinite results in JsonPath transformations
Browse files Browse the repository at this point in the history
...as JsonPath may return a List if multiple elements matched,
even if they were correctly filtered down to a single element.

fixes eclipse-archived#4862
Signed-off-by: Simon Kaufmann <simon.kfm@googlemail.com>
  • Loading branch information
sjsf committed Jan 19, 2018
1 parent 0cc5fb1 commit 4d520d7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
Expand Up @@ -80,4 +80,22 @@ public void testNullValue() throws TransformationException {
assertEquals("NULL", transformedResponse);
}

@Test
public void testIndefinite_filteredToSingle() throws TransformationException {
String transformedResponse = processor.transform("$.*[?(@.name=='bob')].id", jsonArray);
assertEquals("1", transformedResponse);
}

@Test
public void testIndefinite_notFiltered() throws TransformationException {
String transformedResponse = processor.transform("$.*.id", jsonArray);
assertEquals("NULL", transformedResponse);
}

@Test
public void testIndefinite_noMatch() throws TransformationException {
String transformedResponse = processor.transform("$.*[?(@.name=='unknown')].id", jsonArray);
assertEquals("NULL", transformedResponse);
}

}
Expand Up @@ -12,6 +12,8 @@
*/
package org.eclipse.smarthome.transform.jsonpath.internal;

import java.util.List;

import org.eclipse.smarthome.core.transform.TransformationException;
import org.eclipse.smarthome.core.transform.TransformationService;
import org.eclipse.smarthome.core.types.UnDefType;
Expand Down Expand Up @@ -55,7 +57,13 @@ public String transform(String jsonPathExpression, String source) throws Transfo
try {
Object transformationResult = JsonPath.read(source, jsonPathExpression);
logger.debug("transformation resulted in '{}'", transformationResult);
return (transformationResult != null) ? transformationResult.toString() : UnDefType.NULL.toFullString();
if (transformationResult == null) {
return UnDefType.NULL.toFullString();
} else if (transformationResult instanceof List) {
return flattenList((List<?>) transformationResult);
} else {
return transformationResult.toString();
}
} catch (PathNotFoundException e) {
throw new TransformationException("Invalid path '" + jsonPathExpression + "' in '" + source + "'");
} catch (InvalidPathException | InvalidJsonException e) {
Expand All @@ -64,4 +72,14 @@ public String transform(String jsonPathExpression, String source) throws Transfo

}

private String flattenList(List<?> list) {
if (list.size() == 1) {
return list.get(0).toString();
}
if (list.size() > 1) {
logger.warn("The JsonPath expression yielded more than one result: {}", list);
}
return UnDefType.NULL.toFullString();
}

}

0 comments on commit 4d520d7

Please sign in to comment.