2016-11-04 87 views
0

我想解析一個JSON使用速度模板。這裏是我的JSON字符串,速度模板不起作用

{\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} 

這是我的Velocity模板,

$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 

這是被打印輸出。它不打印報告的員工,

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

Employees reporting to him are, 

這裏是Java代碼,

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

} 
+0

您的JSON字符串不是JSON。這只是一個轉義字符串值。 –

+0

添加了Java代碼。 – Deepak

+0

你是否肯定'employees'正在被解析爲JSONArray,或者當你執行'jsonObj.get(keyString)'時是一個可迭代的對象? –

回答

1

由於$employees是一個JSONArray,我看到了兩個可能的原因:

  • 您正在使用一個版本的Apache Velocity在1.7之前(支持Iterable接口在Velocity 1.7中添加)
  • 您正在使用json.org版本terior到20150729(這是其中Iterable接口被添加到JSONArray類的版本)
+0

謝謝!速度版本已過時。升級到2.0,現在工作正常。 – Deepak