问题
I am trying to parse an expression by using Spring Expression Language.
if myVariable
value is set to "first-name" (value with hyphen) then getting class.org.springframework.expression.spel.SpelParseException
.
ExpressionParser parser = new SpelExpressionParser();
String parsedDynamicVariablesValue = parser.parseExpression("#" + myVariable).getValue(stdContext, String.class);
how to solve issue with the hyphen?
Reference Used:
Spring Expression Language (SpEL)
回答1:
It doesn't work that way, you are trying to parse #first-name
- just like Java, you can't have hyphens in variable names.
回答2:
we can provide hyphens or dash in the expressions inside square bracket with quotes. something below like this would work.
String expressionString = "#{response.headers['header-1']}";
Eg:
String response = "{\"response\":{\"headers\":{\"header-1\":\"header2\",\"header1\":\"header1\"},\"body\":{\"body\":\"body\"}}}";
String expressionString = "#{response.headers['header-1']}";
ExpressionParser parser = new SpelExpressionParser();
DefaultConversionService conversionService = new DefaultConversionService();
conversionService.addConverter(new Converter<JsonPropertyAccessor.ToStringFriendlyJsonNode, String>() {
public String convert(JsonPropertyAccessor.ToStringFriendlyJsonNode source) {
return source.toString();
}
});
StandardTypeConverter standardTypeConverter = new StandardTypeConverter(conversionService);
StandardEvaluationContext context = new StandardEvaluationContext();
context.setTypeConverter(standardTypeConverter);
JsonPropertyAccessor jsonPropertyAccessor = new JsonPropertyAccessor();
context.addPropertyAccessor(jsonPropertyAccessor);
context.setRootObject(response);
TemplateParserContext templateParserContext = new TemplateParserContext();
Expression expression = parser.parseExpression(expressionString, templateParserContext);
System.out.println(expression.getValue(context));
OUTPUT: header2
来源:https://stackoverflow.com/questions/44122683/spring-expression-language-spel-is-not-working-when-hyphen-is-used