Java 将 Map<String, Object> 转换为 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26911603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:30:46  来源:igfitidea点击:

Converting Map<String, Object> to json

javajsonjspgson

提问by Razib

I have a map called responseObj

我有一个名为 responseObj 的地图

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

I have added some value in the responseObj like this -

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

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

The userListis a list or users -

userList是一个列表或用户 -

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

The user Object from the User class -

来自 User 类的用户对象 -

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

Now I have some questions -

现在我有一些问题——

  1. Is it possible to convert the responseObjto 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 Objectin the responseObj?

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

  1. 是否有可能转换responseObj成JSON,以便"canApprove""approvers"成为JSON的关键(见下面的代码snippent),我该怎么做呢?

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

    ] }

  2. 如果我把它转换成JSON,并从JSP的响应可以我能够获得在JSP中相应的布尔其中"canApprove"是指的ObjectresponseObj

  3. 我可以"userId" and "roleId"UserClass持久化到 JSON吗?

采纳答案by ToYonos

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)

(格式化)

回答by Attila Neparáczki

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

回答by Safrain

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

您可以使用一些 json 序列化库来为您完成这项工作,例如fastjsongson

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

1. 将依赖 jars 导入到你的项目中,<dependency>如果你使用的是 maven,则在你的 pom.xml 中添加一个节点,或者简单地将 jar 放在你项目的库文件夹中

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

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

回答by seballos

You can try to use JSONObject to parse the map to JSON.

您可以尝试使用 JSONObject 将映射解析为 JSON。

The maven dependency is:

Maven 依赖项是:

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>

later create a new JSON object and pass the map

稍后创建一个新的 JSON 对象并传递地图

JSONObject obj = new JSONObject(responseObj);

and return the object to this web client.

并将对象返回到此 Web 客户端。