考虑我已经将JSON字符串解析为Map<String, Object>
,这是任意嵌套的
我的JSON看起来像:
{
"root": [
{"k":"v1"},
{"k":"v2"}
]
}
我尝试了表达式root.?[k == 'v1']
,但收到了以下错误:
EL1008E: Property or field 'k' cannot be found on object of type 'java.util.LinkedHashMap' - maybe not public?
答案 0 :(得分:1)
评估上下文需要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));
}
结果:
[{k=v1}]
如果没有MapAccessor
,则需要
"['root'].?[['k'] == 'v1']"
MapAccessor
仅适用于不包含句点的地图键。