Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON using Spring SPEL

Can someone tell me why this does not work:

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

I get error "org.springframework.expression.spel.SpelEvaluationException: EL1006E: Function 'jsonPath' could not be found"

And I have following jar in classpath:

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

The SPEL documentation did not help me.

like image 648
elBastarde Avatar asked Sep 21 '18 15:09

elBastarde


People also ask

What is the use of SpEL in spring?

The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.

What can you reference using SpEL?

SpEL can be used independently with the usage of ExpressionParser and EvaluationContext or can be used on top of fields, method parameters, constructor arguments via @Value annotation @Value("#{ … }") . SpEL expressions are usually interpreted during runtime, this is good since it provides a lot of dynamic features.

Which of the following can be used to fetch the value of SpEL?

getValue(); ExpressionParser is responsible for parsing expression strings. In this example, SpEL parser will simply evaluate the string 'Any String' as an expression.


1 Answers

Such a #jsonPath() SpEL function is a part of Spring Integration infrastructure: https://docs.spring.io/spring-integration/docs/current/reference/html/spel.html#spel-functions.

It's not going to work with the plain Spring and only SpEL.

However I see that you use a JsonPropertyAccessor. This one indeed a part of Spring Integration and you definitely have that in your classpath.

From here I think you just miss to register a SpEL function into the 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));
like image 122
Artem Bilan Avatar answered Oct 05 '22 07:10

Artem Bilan