我有一张叫做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)