简体   繁体   中英

Converting Map<String, Object> to json

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 -

  1. 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 }, 

    ] }

  2. 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 an Object in the responseObj ?

  3. Can I persist the "userId" and "roleId" to JSON from User Class?

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}

(formatted)

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.

new com.google.gson.Gson().toJson(responseObj);

You can use some json serialization libraries to do this work for you, like fastjson or gson

1.Import the dependency jars into your project, add a <dependency> node into you pom.xml if you are using maven, or simply drop the jar in you project's library folder

2. String jsonString = JSON.toJSONString(responseObj); (using fastjson)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM