gpt4 book ai didi

java - 速度模板不起作用

转载 作者:行者123 更新时间:2023-12-02 03:15:12 26 4
gpt4 key购买 nike

我正在尝试使用速度模板解析 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);
}

}

最佳答案

由于 $employees 是一个 JSONArray,我发现有两个可能的原因:

  • 您使用的是 Apache Velocity 1.7 之前的版本(Velocity 1.7 中添加了对 Iterable 接口(interface)的支持)
  • 您使用的是 20150729 之前的 json.org 版本(该版本将 Iterable 接口(interface)添加到 JSONArray 类中)

关于java - 速度模板不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40430133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com