我正在使用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 ...]...

任何帮助将不胜感激。
谢谢

最佳答案

最终使用了Aleksandr的建议并添加了空检查。

<#list payload.businessAddress as businessAddress>

   <#if (businessAddress.details??) >
       <EntityLocation>
          <nc:Location id="${businessAddress.details.id}" dataid="${businessAddress.id}">
          </nc:Location>
       </EntityLocation>
   </#if>
</#list>

10-05 23:21