0

Hi i am trying to get array of Objects with question and answer pairs as shown in expected output. Here odd position will be questions and even positions will be answers.

i have a below code

      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);
}

in .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

Actual output

["Question1" ,"Answer1", "Question2", "Answer2" ]

Excepted output- i want like below JSON output from .vm file

  [{"Question1":"Answer1"},{"Question2":"Answer2"}]
daisy
  • 357
  • 3
  • 7
  • 22
  • But you have 1 array with 4 Strings, you need use array with 2 objects which each Object accept 2 String parameters – Ori Marko Jul 16 '18 at 07:15
  • @user7294900 yes, i need to modify single array to array of objects. In single array, odd position will be questions and even position will be answers. It will be dynamic. There could be more than 4 strings in array. – daisy Jul 16 '18 at 07:22

0 Answers0