Search code examples
javajsonjspstruts2ognl

Iterating JSON string using Struts2 iterator - getting nothing printed


I have created an application in Struts 2 for displaying by iterating a JSONObject object taken from Struts2 session by using Struts2 iterator like as shown below

<s:iterator var="menu" value="userMenu.get('permissions')">
   <s:property value="menu.name"/>
</s:iterator>

but I am getting nothing printed

Is there any other alternatives if it is not possible by Struts2 iterator?

my JSON is shown below

{
  "id": 10,
  "groupName": "manager",
  "permissions": [
    {
      "id": 18,
      "name": "Group 1",
      "modules": [
        {
          "id": 6,
          "name": "Company 1",
          "groupId": 18,
          "stat": true,
          "moduleGrpName": "Group 1"
        },
        {
          "id": 8,
          "name": "Company 2",
          "groupId": 18,
          "stat": true,
          "moduleGrpName": "Group 1"
        }
      ],
      "stat": "false"
    },
    {
      "id": 19,
      "name": "Group 2",
      "modules": [
        {
          "id": 17,
          "name": "Company 3",
          "groupId": 19,
          "stat": true,
          "moduleGrpName": "Group 2"
        },
        {
          "id": 15,
          "name": "Company 4",
          "groupId": 19,
          "stat": true,
          "moduleGrpName": "Group 2"
        }
      ],
      "stat": "false"
    }
  ]
}

EDIT:

 public String validateLogin() throws Exception 
    {
        TableUser flag=hobjLoginauth.checkUsercredentials(userName, password);
        System.out.println("Flag :"+flag);
        if(flag == null!=true)
        {
            sessionmap.remove("logincheck");
            setSession(sessionmap);
            sessionmap.put("userId", flag.getId());
            sessionmap.put("user",flag.getUsername());
            sessionmap.put("userMenu", new JSONObject(userModulesServicesImpl.getDeSerialized(flag.getGroupId().getPermissions())));
            sessionmap.put("menuGroups",userModulesServicesImpl.getUserModules());
            return SUCCESS;
        }else{
            sessionmap.put("logincheck","1");
            return ERROR;
        }

    }

Solution

  • You can use the following getter for JSON

    public Map getUserMenu(){     
      return JSONObject.fromObject(json);
    }
    

    also you can do the same using Struts2 utility

    public Map getUserMenu(){
      Map res = null;
      try {
        Object o = JSONUtil.deserialize(json);
        res = (Map)o;
      } catch (JSONException e) {
        e.printStackTrace();
      }
      return res;
    }
    

    and iterate a map via

    <s:iterator var="menu" value="userMenu.get('permissions')">
      <s:property value="#menu.name"/>
    </s:iterator>
    

    Note that using variable of the iterator is not necessary but if used then it accessed from the value stack context using #.