Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring EL: Safe navigation with map access

I'm using Spring EL to pull values out of a rather complex set of nested maps and lists. I want to be able to use an expression like

[9]['firstSubKey']['secondSubKey']

except that [9]['firstSubKey'] might be null. I can't figure out how to use the safe navigation correctly: I tried

[9]['firstSubKey']?['secondSubKey']

and

[9]['firstSubKey']?.['secondSubKey']

and both returned some kind of parse error. I eventually got it to work by using

[9]['firstSubKey']?.get('secondSubKey')

but that feels tacky. Is there a better way or is this just a feature SpringEL doesn't have? I'm using Spring 3.1.3.

Relatedly, if I have a list/array of an unknown number of elements, is there a way to check for that safely? IE if I have an array of 4 elements, I want [5] to return null. As is, it throws a SpelEvaluationException.

like image 278
Dan Avatar asked Mar 21 '13 17:03

Dan


1 Answers

I couldn't come up with a better solution to yours; only

"['0']['a'] != null ? ['0']['a']['b'] : null"

and

"size() > 5 ? [5] : null"

like image 200
Gary Russell Avatar answered Oct 12 '22 19:10

Gary Russell