嗨,我正在尝试获取包含问题和答案对的对象数组,如预期输出所示。在这里,奇数位置将是问题,偶数位置将是答案。
我有一个下面的代码
public static void main(String args[]) throws Exception {
VelocityEngine engine = new VelocityEngine();
engine.init();
Template template = engine.getTemplate("userinfo.vm");
VelocityContext vc = new VelocityContext();
String[] myArray = {"Question1","Answer1","Question2","Answer2"};
vc.put("arr", myArray);
StringWriter writer = new StringWriter();
template.merge(vc, writer);
System.out.println(writer);
}
在.vm中的
#set($myArr = $arr)
[
#foreach($x in $myArr)
#VelToJSON($x)
#if($foreachCount != $myArr.size()) , #end
#end
]
##TODO: Make it not treat numbers as strings
#macro(VelToJSON $item)
#if($item.keySet())
#VelListToJSON($item)
#elseif($item.size())
#VelArrayToJSON($item)
#elseif($item == true || $item ==false)
$item
#else
"$item"
#end
#end
["Question1" ,"Answer1", "Question2", "Answer2" ]
[{"Question1":"Answer1"},{"Question2":"Answer2"}]