Converting Map<String, Object> to json
Solution 1
Try this :
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;
}
}
Test :
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));
Prints :
{"approvers":[{"userId":1,"roleId":1},{"userId":2,"roleId":2}],"canApprove":true}
Solution 2
You can try to use JSONObject to parse the map to JSON.
The maven dependency is:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
later create a new JSON object and pass the map
JSONObject obj = new JSONObject(responseObj);
and return the object to this web client.
Solution 3
new com.google.gson.Gson().toJson(responseObj);
Razib
Updated on November 14, 2020Comments
-
Razib over 3 years
I have a map called responseObj
Map<String, object> responseObj = new HashMap<String, Object>();
I have added some value in the responseObj like this -
responseObj.put("canApprove", true); //1 responseObj.put("approvers", userList);
The
userList
is a list or users -List<User> userList = new ArrayList<User>();
The user Object from the User class -
class User { private int userId; private int roleId; }
Now I have some questions -
Is it possible to convert the
responseObj
to a json so that"canApprove"
and"approvers"
become key of json (see the code snippent below) and how can I make it?{ "canApprove" : true, "approver": [ { "userId": 309, "roleId": 2009 }, { "userId": 3008, "roleId": 2009 },
] }
If I convert it into a json and get the response from jsp can I able get the appropriate boolean in jsp where the
"canApprove"
refers anObject
in theresponseObj
?Can I persist the
"userId" and "roleId"
to JSON fromUser
Class?
-
Razib over 9 yearsDoes this method satisfy the question 3(I have add the question 3 later). Thanks for your answer
-
Attila Neparáczki over 9 yearsYes. You will be surprised how well Gson works. At least i was, really intuitive
-
Razib over 9 yearswhich library are you using for this example?
-
Razib over 9 yearsThanks for your response