Разбор JSON с использованием Spring SPEL - PullRequest
0 голосов
/ 21 сентября 2018

Может кто-нибудь сказать мне, почему это не работает:

@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: Не удалось найти функцию 'jsonPath'"

И у меня есть следующий jar в classpath:

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

Документация SPEL мне не помогла.

1 Ответ

0 голосов
/ 21 сентября 2018

Такая #jsonPath() функция SpEL является частью инфраструктуры Spring Integration: https://docs.spring.io/spring-integration/docs/current/reference/html/spel.html#spel-functions.

Она не будет работать с простым Spring и только с SpEL.

Однако я вижу, чтоВы используете JsonPropertyAccessor.Это действительно часть Spring Integration, и у вас определенно есть это в вашем classpath.

Отсюда я думаю, что вам просто не хватает зарегистрировать функцию SpEL в StandardEvaluationContext: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#expressions-ref-functions

context.registerFunction("jsonPath", BeanUtils.resolveSignature("evaluate", JsonPathUtils.class));
...