我使用freemarker生成xml输出并且在访问"Stack Overflow"上的文章时遇到了嵌套对象属性的问题,但我仍然无法获取属性并获得无效的引用表达。
代码示例
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());
}
}
并且freemarker模板是
<#list payload.businessAddress as businessAddress>
<EntityLocation>
<nc:Location id="${businessAddress}Sub${details.id}" dataid="${businessAddress.id}">
</nc:Location>
</EntityLocation>
</#list>
甚至
<#list payload.businessAddress as businessAddress>
<EntityLocation>
<nc:Location id="${businessAddress}Sub${getDetails().id}" dataid="${businessAddress.id}">
</nc:Location>
</EntityLocation>
</#list
我收到的例外是
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 ...]...
非常感谢任何帮助。 感谢
答案 0 :(得分:1)
使用Aleksandr建议的内容以及添加的空检查结束。
<#list payload.businessAddress as businessAddress>
<#if (businessAddress.details??) >
<EntityLocation>
<nc:Location id="${businessAddress.details.id}" dataid="${businessAddress.id}">
</nc:Location>
</EntityLocation>
</#if>
</#list>