在速度模板中将数组转换为JSON对象

时间:2018-07-16 06:28:09

标签: arrays json velocity velocity-template-language

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

我有一个下面的代码

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

0 个答案:

没有答案