【问题标题】:Parse JSON using Spring SPEL使用 Spring SPEL 解析 JSON
【发布时间】:2019-02-26 00:34:58
【问题描述】:

谁能告诉我为什么这不起作用:

@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);
}

我收到错误“org.springframework.expression.spel.SpelEvaluationException: EL1006E: Function 'jsonPath' could not be found”

我在类路径中有以下 jar:

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
    </dependency>

SPEL 文档对我没有帮助。

【问题讨论】:

    标签: spring spring-integration jsonpath spring-el


    【解决方案1】:

    这样的#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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-20
      • 2016-06-27
      • 2017-08-01
      • 1970-01-01
      • 2012-05-24
      • 2011-08-26
      • 2020-04-04
      • 1970-01-01
      相关资源
      最近更新 更多