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);
}
}
您的JSON字符串不是JSON。這只是一個轉義字符串值。 –
添加了Java代碼。 – Deepak
你是否肯定'employees'正在被解析爲JSONArray,或者當你執行'jsonObj.get(keyString)'時是一個可迭代的對象? –