在customAttributes中返回JSON数组

问题描述:

继我的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"} 

为了做到这一点,你需要转换的组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 
    }; 
}