echen
echen

Reputation: 2072

Spring Expression Directly access map keys in Selection

Consider that I have parsed a JSON String to a Map<String, Object>, which is arbitrarily nested

My JSON looks like:

{
  "root": [
   {"k":"v1"},
   {"k":"v2"}
  ]
}

I tried the expression root.?[k == 'v1'], however received the following error:

EL1008E: Property or field 'k' cannot be found on object of type 'java.util.LinkedHashMap' - maybe not public?

Upvotes: 0

Views: 1491

Answers (1)

Gary Russell
Gary Russell

Reputation: 174664

The evaluation context needs a MapAccessor:

public static void main(String[] args) throws Exception {
    String json = "{\n" +
            "  \"root\": [\n" +
            "   {\"k\":\"v1\"},\n" +
            "   {\"k\":\"v2\"}\n" +
            "  ]\n" +
            "}";
    ObjectMapper mapper = new ObjectMapper();
    Object root = mapper.readValue(json, Object.class);
    Expression expression = new SpelExpressionParser().parseExpression("root.?[k == 'v1']");
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.addPropertyAccessor(new MapAccessor());
    System.out.println(expression.getValue(ctx, root));
}

result:

[{k=v1}]

Without a MapAccessor, you need

"['root'].?[['k'] == 'v1']"

A MapAccessor will only work with map keys that don't contain periods.

Upvotes: 2

Related Questions