Question

Following on from my previous question, I can return a list of groups in the custom attributes section, however I'd like to know what I need to do to return them in a std JSON structure.

If I send back a Java List

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);

Then the client receives

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

If I add the groups in a 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);

I get the following response in the client

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

What I'd really like to get is something like this

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

Solution

In order to do this, you'll need to convert the groups HashMap into a JSON object before putting it into your attributes HashMap.

Something like:

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

The syntax for converting the HashMap to a JSONObject will vary depending on which JSON library your project has access to. If it does not have a method built in, then you will have to manually loop through your HashMap in order to convert it into a proper JSONObject.

Edit:

Since the groups object is being passed in as a string, you can use JSON.parse to convert it into a JSON object.

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

    return {
        groups: groups
    };
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top