gpt4 book ai didi

freemarker - 访问 freemarker 中的嵌套对象

转载 作者:行者123 更新时间:2023-12-02 03:32:19 45 4
gpt4 key购买 nike

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

关于freemarker - 访问 freemarker 中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25876446/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com