Using property references that might be null in expressions can lead to unexpected results. This topic contains examples and how to handle them.
The examples in this topic use the following data model.
{
"user": {
"name": {
"given": "John",
"family": "Doe"
}
}
String concatenation
- Issue
-
Because
user.name.middle
is null, the expressionuser.name.given + ', ' + user.name.middle + ', ' + user.name.family
returns John, null, Doe. - Solution to concatenate only non-null values
-
#string.join({user.name.given, user.name.middle, user.name.family}, ', ')
returns John, Doe. - Issue
-
Because
user.age
is null and the other operand is numeric, the expression3 + user.age
returns an error. - Solution to avoid errors using an Elvis operator to add a default value
-
3 + (user.age ?: '')
returns 3.
Creating an array using nullable values
- Issue
-
The newly created array
{user.externalId}
returns [ null ]. - Solution to remove nulls from the newly created array
-
#data.removeAll({user.externalId}, {null})
returns [].
Ternary operator
- Issue
-
Because
user.enabled
is null, the expressionuser.enabled ? 'Active' : 'Inactive'
returns an error. - Solution to avoid errors using an Elvis operator to add a default value
-
(user.enabled ?: false) ? 'Active' : 'Inactive'
returns Inactive.