使用 Spring SPEL 解析 JSON
Parse JSON using 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: Function 'jsonPath' could not be found"
我在类路径中有以下 jar:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
</dependency>
SPEL 文档对我没有帮助。
这样的 #jsonPath()
SpEL 函数是 Spring 集成基础结构的一部分:https://docs.spring.io/spring-integration/docs/current/reference/html/spel.html#spel-functions。
它不适用于普通的 Spring 且仅适用于 SpEL。
不过我看到你用的是 JsonPropertyAccessor
。这确实是 Spring 集成的一部分,您的类路径中肯定有它。
从这里我认为您只是错过了将 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));
谁能告诉我为什么这不起作用:
@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 文档对我没有帮助。
这样的 #jsonPath()
SpEL 函数是 Spring 集成基础结构的一部分:https://docs.spring.io/spring-integration/docs/current/reference/html/spel.html#spel-functions。
它不适用于普通的 Spring 且仅适用于 SpEL。
不过我看到你用的是 JsonPropertyAccessor
。这确实是 Spring 集成的一部分,您的类路径中肯定有它。
从这里我认为您只是错过了将 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));