在Freemarker中将java.lang.Iterable视为#list表达式 [英] Treat a java.lang.Iterable as a #list expression in Freemarker

查看:187
本文介绍了在Freemarker中将java.lang.Iterable视为#list表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java.lang.Iterable(实际上是com.google.gson.JsonArray实例).

I have a java.lang.Iterable (in fact, a com.google.gson.JsonArray instance).

我想使用freemarker(2.3.16)枚举列表中的项目.

I would like to enumerate the items in the list using freemarker (2.3.16).

[#assign sports = controller.sports]
[#-- At this point, sports is bound to a com.google.gson.JsonArray instance. --]

[#list sports as sport]
  ${sport_index}
[/#list]

我想避免只写一个自定义bean和Gson反序列化器就可以得到一个显式的项目集合.使用Gson(已经为我将JSON字符串反序列化为JsonObject)然后从该JsonObject创建我自己的DAG对象对我来说似乎很浪费.

I would like to avoid having to write a custom bean and Gson deserializer just to have an explicit collection of items. Using Gson (which already deserializes the JSON string to a JsonObject for me) to then create my own DAG of objects from that JsonObject seems wasteful to me.

不幸的是,我无法找到一种方法使Freemarker将java.lang.Iterable视为列表.我得到:

Unfortunately, I haven't been able to work out a way of getting Freemarker to treat the java.lang.Iterable as a list. I get:

freemarker.template.TemplateException : Expected collection or sequence.
  controller.sports evaluated instead to freemarker.ext.beans.XMLStringModel on line 8, column 16 in sports.html.
freemarker.core.TemplateObject.invalidTypeException(line:135)
freemarker.core.IteratorBlock$Context.runLoop(line:190)
freemarker.core.Environment.visit(line:417)
freemarker.core.IteratorBlock.accept(line:102)
freemarker.core.Environment.visit(line:210)

推荐答案

明确循环遍历迭代器应该可以,例如:

Explicitly looping over the iterator should work, e.g.:

[#list sports.iterator() as sport]
   ${sport_index}
[/#list]

这篇关于在Freemarker中将java.lang.Iterable视为#list表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆