使用 Spring SPEL 解析 JSON

elB*_*rde 5 spring spring-integration jsonpath spring-el

有人可以告诉我为什么这不起作用:

@Test
public void should_parse_json() {
    Expression expression = new SpelExpressionParser().parseExpression("#jsonPath(get('JsonData'), '$.someData')");

    Map<String, Object> data = new HashMap<>();
    data.put("JsonData", "{\"someData\": 100}");

    StandardEvaluationContext context = new StandardEvaluationContext(data);
    context.addPropertyAccessor(new JsonPropertyAccessor());

    assertThat(expression.getValue(context, Object.class)).isEqualTo(100);
}
Run Code Online (Sandbox Code Playgroud)

我收到错误“org.springframework.expression.spel.SpelEvaluationException:EL1006E:找不到函数‘jsonPath’”

我在类路径中有以下 jar:

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

SPEL 文档对我没有帮助。

Art*_*lan 6

这样的#jsonPath()SpEL 函数是 Spring Integration 基础设施的一部分:https ://docs.spring.io/spring-integration/docs/current/reference/html/spel.html#spel-functions 。

它不适用于普通的 Spring,只能使用 SpEL。

但是我看到您使用JsonPropertyAccessor. 这确实是 Spring Integration 的一部分,您的类路径中肯定有它。

从这里开始,我认为您只是错过将 SpEL 函数注册到StandardEvaluationContexthttps : //docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#expressions-ref-functions

context.registerFunction("jsonPath", BeanUtils.resolveSignature("evaluate", JsonPathUtils.class));
Run Code Online (Sandbox Code Playgroud)