gpt4 book ai didi

java - 具有 pojo 的 Freemarker HashMap 循环

转载 作者:行者123 更新时间:2023-12-01 04:50:44 25 4
gpt4 key购买 nike

我有 HashMap 汽车,并且 pojo Car 包含属性“engines”,这又是 HashMap。

public class Car implements Serializable{
private Long id;
private String name;
private Map<Long,Engine> engines = new HashMap<>();
..
..
}
public class Engine implements Serializable{
private Long id;
private String name;
}

Freemarker模型

final StringWriter sw = new StringWriter();
Map model = new HashMap();
model.put("cars",theCarsMap);
Template tmpl = t.cfg.getTemplate("text.ftl");
tmpl.process(model, sw);

Freemarker配置

        cfg = new Configuration();
cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250));
cfg.setClassForTemplateLoading(getClass(), ".");
cfg.setObjectWrapper(new DefaultObjectWrapper());

模板代码:

 <#assign rKeys = cars?keys>
<#list rKeys as rKey>
Car Details:${cars[rKey].getName()}\n
--------------------------------------------------\n
<#assign engines = cars[rKey].getEngines()>
<#assign tKeys = engines?keys>
<#list tKeys as tKey>
------------------Engine Details-----------------\n
Name: ${engines[tKey].getName()}\n
</#list>
</#list>

我收到以下错误:

有问题的指令:

${cars[rKey].getName()} [on line 3, column 18 in text.ftl]

是否有与包含 pojos 和另一个 Map 的 HashMap 相关的特殊处理?

最佳答案

它不适用于以 POJO 作为值的 Map,我必须更改为 List...。而且原始类型的 Java 对象包装器也不起作用,请更改为原始定义。即长 ---> 长

<#list cars as c>
${c.id!'Unknown'} - ${c.name!'Unknown'}

<#list c.engineList as t>
${t.id!'Unknown'} - ${t.name!'Unknown'}
</#list>
</#list>

关于java - 具有 pojo 的 Freemarker HashMap 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15012238/

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