Chandra Sekhar
Chandra Sekhar

Reputation: 16516

Spring Expression Language (SpEL) is not working when hyphen is used

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)

Upvotes: 1

Views: 2692

Answers (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

Upvotes: 0

Gary Russell
Gary Russell

Reputation: 174504

It doesn't work that way, you are trying to parse #first-name - just like Java, you can't have hyphens in variable names.

Upvotes: 2

Related Questions