我有一张叫做responseObj的地图

Map<String, object> responseObj = new HashMap<String, Object>();


我像这样在responseObj中添加了一些值-

responseObj.put("canApprove", true); //1
responseObj.put("approvers", userList);


userList是一个列表或用户-

List<User> userList = new ArrayList<User>();


用户类中的用户对象-

class User {
 private int userId;
 private int roleId;
}


现在我有一些问题-


是否可以将responseObj转换为json,以使"canApprove""approvers"成为json的键(请参见下面的代码片段),我该怎么做?

{
 "canApprove" : true,
 "approver": [
{
  "userId": 309,
  "roleId": 2009
},
{
  "userId": 3008,
  "roleId": 2009
},


]
}
如果我将其转换为json并从jsp获得响应,是否可以在jsp中获取适当的布尔值,其中"canApprove"Object中引用responseObj
我可以将"userId" and "roleId"User类持久化为JSON吗?

最佳答案

试试这个 :

public static class User
{
    public User(int userId, int roleId)
    {
        this.userId = userId;
        this.roleId = roleId;
    }
    private int userId;
    private int roleId;
    public int getUserId()
    {
        return userId;
    }
    public int getRoleId()
    {
        return roleId;
    }
    public void setUserId(int userId)
    {
        this.userId = userId;
    }
    public void setRoleId(int roleId)
    {
        this.roleId = roleId;
    }
}


测试:

Map<String, Object> responseObj = new HashMap<String, Object>();
List<User> userList = new ArrayList<User>();
userList.add(new User(1, 1));
userList.add(new User(2, 2));
responseObj.put("canApprove", true); //1
responseObj.put("approvers", userList);

System.out.println(new JSONObject(responseObj));


版画:

{"approvers":[{"userId":1,"roleId":1},{"userId":2,"roleId":2}],"canApprove":true}


(formatted)

09-27 23:13