Accessing nested object in freemarker
I am using freemarker to generate xml output and problems with accessing properties of nested objects. I came across this article on Stack Overflow , but I still can't get properties and get an invalid reference expression.
Sample code
public class Inc {
private String id;
private List<BusinessAddress> businessAddress;
....
//get and setters for properties
....
}
//------------------------------
public class BusinessAddress{
private String id;
private Address details;
....
//get and setters for properties
....
}
//------------------------------
public class Address {
private String id;
//get and setters for properties
....
}
//--------------------------------------
public class FreemarkerTest {
public static void main(String[] args) {
try
{
Inc inc = ......;
Template freemarkerTemplate = null;
Configuration configuration = new Configuration();
configuration.setClassForTemplateLoading(FreemarkerTest.class, "/");
String templateFile = "freemarker/template.ftl";
StringWriter out = new StringWriter();
freemarkerTemplate = configuration.getTemplate(templateFile);
Map<String,Object> contextPropsExpressioned = new HashMap<String,Object>();
contextPropsExpressioned.put("payload", inc);
freemarkerTemplate.process(contextPropsExpressioned, out);
System.out.println(out);
out.flush();
out.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
and freemarker template
<#list payload.businessAddress as businessAddress>
<EntityLocation>
<nc:Location id="${businessAddress}Sub${details.id}" dataid="${businessAddress.id}">
</nc:Location>
</EntityLocation>
</#list>
even
<#list payload.businessAddress as businessAddress>
<EntityLocation>
<nc:Location id="${businessAddress}Sub${getDetails().id}" dataid="${businessAddress.id}">
</nc:Location>
</EntityLocation>
</#list
The exception I am getting is
FreeMarker template error:
The failing instruction (FTL stack trace):
----------
==> ${details.id} [in template "freemarker/template.ftl" at line 172, column 97]
----------
Tip: If the failing expression is known to be legally null/missing, either specify a default value.....
Java stack trace (for programmers):
----------
freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...]...
Any help would be greatly appreciated. Thanks to
+3
source to share
1 answer
Ended up using the one suggested by Alexander, and added zero checks.
<#list payload.businessAddress as businessAddress>
<#if (businessAddress.details??) >
<EntityLocation>
<nc:Location id="${businessAddress.details.id}" dataid="${businessAddress.id}">
</nc:Location>
</EntityLocation>
</#if>
</#list>
+1
source to share