2013-11-26 18 views
0

繼我的previous question之後,我可以返回自定義屬性部分中的組列表,但是我想知道我需要做什麼才能將它們返回到std JSON結構中。在customAttributes中返回JSON數組

如果我發回一個Java列表

HashMap<String, Object> customAttributes = new HashMap<String, Object>(); 
customAttributes.put("AuthenticationDate", new Date()); 
List<String> groups = new ArrayList<String>(); 
groups.add("Users"); 
groups.add("Managers"); 
customAttributes.put("Groups", groups); 
UserIdentity identity = new UserIdentity(loginModule, USERNAME, "Fred Flintstone", null, customAttributes, PASSWORD); 

然後客戶端收到

{"Groups":"[Users, Managers]","AuthenticationDate":"Tue Nov 26 12:07:37 EST 2013"} 

如果我在一個HashMap

List<Map<String, Object>> groups = new ArrayList<Map<String, Object>>(); 
HashMap<String, Object> groupMap1 = new HashMap<String, Object>(); 
groupMap1.put("id", "Users"); 
groups.add(groupMap1); 
HashMap<String, Object> groupMap2 = new HashMap<String, Object>(); 
groupMap2.put("id", "Managers"); 
groups.add(groupMap2); 
customAttributes.put("Groups", groups); 

UserIdentity identity = new UserIdentity(loginModule, USERNAME, "Fred Flintstone", null, customAttributes, PASSWORD); 

我得到以下響應添加組客戶端

"attributes":{"Groups":"[{id=Users}, {id=Managers}]","AuthenticationDate":"Tue Nov 26 12:13:40 EST 2013"} 

我真的很想得到的是這樣的

"attributes":{"Groups":[{"id" : "Users"}, {"id" :"Managers"}],"AuthenticationDate":"Tue Nov 26 12:13:40 EST 2013"} 

回答

1

爲了做到這一點,你需要轉換的組HashMap類成JSON對象把它變成你的屬性的HashMap之前。

喜歡的東西:

... 
groups.add(groupMap1); 
groups.add(groupMap2); 
customAttributes.put("Groups", JSONObject(groups)); 

的HashMap中轉換成一個JSONObject將根據其JSON庫項目先後獲得改變的語法。如果它沒有內置的方法,那麼你將不得不手動循環你的HashMap,以便將其轉換爲適當的JSONObject。

編輯:

由於組對象被傳遞作爲一個字符串,你可以使用JSON.parse把它轉換成一個JSON對象。

function getSecretData(){ 
    var user = WL.Server.getActiveUser(); 
    var attributes = user.attributes; 
    var groups = JSON.parse(attributes.Groups); 

    return { 
     groups: groups 
    }; 
}