Tip: Generate XML with Velocity template with array/list data

Spent some time with null checks in the velocity template and would like to share the findings:

If you have data in an array such as this example:

[
    {
        "Lines": [
            {
                "TEST1": null,
                "TEST2": "Text"
            }
        ]
    }
]

If you try to do a null and empty value check using standard velocity methods (such as this) you will run in to problems when the input data is from an array.

Normally when doing null and empty checks you can simply use

#if($TEST1 && $TEST1 != "")
dosomething
#end

But when processing data in the array this will not work (the evaluation will be true even if the JSON input value is null:

#if($Lines[0].TEST1 && $TEST1 != "")
dosomething
#end

This will work (null value, empty value or if the variable does not exist in the array):

#if($Lines[0].TEST1 != "***NO DATA***" && $Lines[0].TEST1 != "")
dosomething
#end

Same think if you are in a #foreach loop

#foreach($Line in $Lines)
  #if($Line.TEST1 != "***NO DATA***" && $Line.TEST1 != "")
    dosomething
  #end
#end

The thing where the value is set to ***NO DATA*** seem to be a SnapLogic behaviour, maybe someone can confirm this?

I hope this will save someone a few hours.

2 Likes

Thanks for sharing @JKarlsson and good investigative work!