Search code examples
javajsonvelocity

Velocity Template Not working


I am trying to parse a json using velocity template. Here is my json string,

{\n  \"firstName\": \"Tom\",\n  \"lastName\": \"Geller\",\n  \"department\": \"Retail\",\n  \"manager\": \"Steve\",\n  \"joiningDate\": \"03/08/2011\",\n  \"employees\": [\n    {\n      \"firstName\": \"Paul\",\n      \"lastName\": \"Balmer\",\n      \"department\": \"Retail\",\n      \"manager\": \"Tom Geller\",\n      \"joiningDate\": \"06/21/2014\"\n    },\n    {\n      \"firstName\": \"Eric\",\n      \"lastName\": \"S\",\n      \"department\": \"Retail\",\n      \"manager\": \"Tom Geller\",\n      \"joiningDate\": \"09/13/2014\"\n    }\n  ]\n}

This is my velocity template,

$firstName $lastName belongs to $department Department. 
His manager is $manager and joining date is $joiningDate.

Employees reporting to him are, 
#foreach( $employee in $employees )
    $employee.firstName $employee.lastName
#end

This is the output that gets printed. It doesn't print the reporting employees,

Tom Geller belongs to Retail Department. 
His manager is Steve and joining date is 03/08/2011.

Employees reporting to him are, 

Here is the java code,

public class VelocityTemplateDemo {

protected VelocityEngine velocity;

public VelocityTemplateDemo() {
    velocity = new VelocityEngine();
    velocity.init();
}

public String publish(String templatePath, String jsonString) throws IOException {
    JSONObject jsonObj = new JSONObject(jsonString);
    VelocityContext context = new VelocityContext();
    for (Object key : jsonObj.keySet()) {
        String keyString = String.valueOf(key);
        context.put(keyString, jsonObj.get(keyString));
    }
    Writer writer = new StringWriter();
    velocity.mergeTemplate(templatePath, "UTF-8", context, writer);
    writer.flush();
    return writer.toString();
}

public static void main(String[] args) throws IOException {
    String str = "{\n  \"firstName\": \"Tom\",\n  \"lastName\": \"Geller\",\n  \"department\": \"Retail\",\n  \"manager\": \"Steve\",\n  \"joiningDate\": \"03/08/2011\",\n  \"employees\": [\n    {\n      \"firstName\": \"Paul\",\n      \"lastName\": \"Balmer\",\n      \"department\": \"Retail\",\n      \"manager\": \"Tom Geller\",\n      \"joiningDate\": \"06/21/2014\"\n    },\n    {\n      \"firstName\": \"Eric\",\n      \"lastName\": \"S\",\n      \"department\": \"Retail\",\n      \"manager\": \"Tom Geller\",\n      \"joiningDate\": \"09/13/2014\"\n    }\n  ]\n}";
    String result = new VelocityTemplateDemo().publish("/src/main/resources/template.vm", str);
    System.out.println(result);
}

}

Solution

  • Since $employees is a JSONArray, I see two probable causes:

    • You are using a version of Apache Velocity anterior to 1.7 (support for the Iterable interface was added in Velocity 1.7)
    • You are using a version of json.org anterior to 20150729 (it's the version in which the Iterable interface was added to the JSONArray class)