[我正在开发velocty和Java,我是从json文件中获取值的(我使用JSON对象的递归并存储了递归的路径(请参阅下面的上下文以了解想法)]
String hhh="I am a ${root.primaryApplicant.firstName} ${firstName} ";
Velocity.init();
VelocityContext vm=new VelocityContext();
for(String m : mp.keySet())
{
vm.put(m,mp.get(m));
}
StringWriter w = new StringWriter();
Velocity.evaluate( vm, w, "mystring", forma );
地图mp从json文件获得
{
"id": 45288,
"code": null,
"name": null,
"external": false,
"leadReferenceId": "APPID1573716175142",
"createdBy": null,
"createdDate": "2017-10-26T12:14:17.000Z",
"agentName": null,
"ipAddress": null,
"applicationType": "HOME",
"loanType": "HOME",
"applicantType": {
"id": 269,
"code": "Single",
"name": "Single",
"external": false
},
"relationship": null,
"primaryApplicant": {
"id": 45289,
"code": null,
"name": null,
"external": false,
"existingCustomer": null,
"customerId": null,
"partyRoleType": {
"id": 348,
"code": "0",
"name": "PRIMARY",
"external": false
},
"partyRelationshipType": null,
"salutation": {
"id": 289,
"code": "MR",
"name": "Mr",
"external": false
},
"firstName": "Anuj",
"middleName": "",
"lastName": "singh",
"dateOfBirth": "1986-12-11T18:30:00.000Z",
"genderType": {
使用调试器,虚拟机包含的上下文
"root.primaryApplicant.firstName" -> "Anuj"
"firstName" -> "Anuj"
速度评估后,我得到
"I am a ${root.primaryApplicant.firstName} Anuj ";
我假设它不能用替换键。在两者之间。有没有更好的方法来填充字符串
速度文件已指定“ root。*”,由于无法编辑它们,因此我正在使用以下递归程序来获取键
private static void rexuse(String a,Map<String, Object> mp,JSONObject js,String parent) throws JSONException {
Iterator<String> keys = js.keys();
while(keys.hasNext()) {
String key = keys.next();
if(key.equals("name"))
{
mp.put(parent,js.get(key));
}
if (js.get(key) instanceof JSONObject) {
rexuse(a+"."+key,mp,js.getJSONObject(key),key);
}
else
{
if(!mp.containsKey(key) ||( mp.containsKey(key) && mp.get(key)==null))
mp.put(key, js.get(key));
mp.put(a+"."+key, js.get(key) );
}
}
}
其中a是前缀,在上面使用,称为
String a="root";
rexuse(a,mp,js,"root");
这里有不一致之处。
使用您提供的Java初始化代码,Velocity模板应包含:
${primaryApplicant.firstName}
如果要使用${root.primaryApplicant.firstName}
,则另一个引用也应该以root前缀,例如${root.firstName}
,并且Java上下文初始化代码应为:
vm.put("root", mp);
但是在两种情况下,您还必须检查使用的json库是否为Json对象提供了通用的getter,以便'dot'运算符可以递归调用json对象上的Java方法get(<fieldname>)
。有tons of those。