0

嗨,我正在尝试获取带有问题和答案对的对象数组,如预期输出所示。这里奇数位置是问题,偶数位置是答案。

我有以下代码

      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" ]

例外输出-我想像下面的 .vm 文件的 JSON 输出

  [{"Question1":"Answer1"},{"Question2":"Answer2"}]
4

0 回答 0