【发布时间】:2019-11-24 20:59:14
【问题描述】:
我正在尝试使用速度模板解析 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}
这是我的速度模板,
$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代码。
-
您确定
employees被解析为 JSONArray 还是当您执行jsonObj.get(keyString)时是一个可迭代对象? -
将值放入上下文后,我的上下文将所有来自 json 的值保存为 HashMap, {firstName=Tom, lastName=Geller, manager=Steve,joiningDate=03/08 /2011,部门=零售,员工=[{"firstName":"Paul","lastName":"Balmer","manager":"Tom Geller","joiningDate":"06/21/2014","department ":"Retail"},{"firstName":"Eric","lastName":"S","manager":"Tom Geller","joiningDate":"09/13/2014","department":"零售"}]}
-
员工数组中似乎有更多的 HashMap 或其他东西。建议:使用 Jackson 或 Gson 等 JSON 解析器将 JSON 转换为 Velocity 可以理解的 Java 对象。