Разбор JSON с использованием Spring SPEL

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

@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 мне не помогла.

2 ответа

Решение

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

Это не будет работать с простой Spring и только SpEL.

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

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

context.registerFunction("jsonPath", BeanUtils.resolveSignature("evaluate", JsonPathUtils.class));
  1. Добавьте зависимости.
              <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.7.0</version>
        </dependency>
  1. Регистрация функции SpEL
      evaluationContext.registerFunction("jsonPath", BeanUtils.resolveSignature("evaluate", JsonPathUtils.class));
Другие вопросы по тегам