[英]How to populate velocity string with a JSON Object in JAVA?
我正在開發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": {
使用調試器,vm的上下文包含
"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,以便“點”運算符將在json對象上遞歸調用Java方法get(<fieldname>)
。 有很多這些 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.