【问题标题】:Convert from LinkedHashMap to Json String从 LinkedHashMap 转换为 Json 字符串
【发布时间】:2014-05-17 05:26:26
【问题描述】:

我正在使用 Jongo 与 Mongo 一起工作,当我进行查询时,我收到 LinkedHashMap 作为结果。

Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
    LinkedHashMap data = new LinkedHashMap();
    data = (LinkedHashMap) one.next();
    String content = data.toString();
}

问题是如果 json 是 {"user":"something"} 内容将是 {user=something},它不是 json 只是 toString 来自 HashMap 的方法。

我怎样才能得到原始的JSON

我没有class 来映射response,创建map 类也不是解决方案,这就是我使用Object.class. 的原因

【问题讨论】:

  • datos的类型是什么?

标签: java json mongodb linkedhashmap


【解决方案1】:

如果您可以访问一些 JSON 库,似乎就是这样。

如果使用 org.json 库,请使用 public JSONObject(java.util.Map map):

String jsonString = new JSONObject(data).toString()

如果是Gson,使用@hellboy提到的gson.toJson()方法:

String jsonString = new Gson().toJson(data, Map.class);

【讨论】:

【解决方案2】:

您可以使用 Google 的 Gson 库将任何对象转换为 JSON。这是一个将 LinkedHashMap 转换为 json 的示例 -

Gson gson = new Gson();
String json = gson.toJson(map,LinkedHashMap.class);

【讨论】:

    【解决方案3】:

    com.mongodb.BasicDBObject 构造函数之一将 Map 作为输入。然后你只需要在 BasicDBObject 对象上调用 toString()。

    Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
        while (one.hasNext()) {
            LinkedHashMap data= new LinkedHashMap();
    
            data= (LinkedHashMap) one.next();
    
            com.mongodb.BasicDBObject bdo = new com.mongodb.BasicDBObject(data);    
            String json = bdo.toString();
        }
    

    【讨论】:

      【解决方案4】:

      我使用以下代码解决了这个问题:

          Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
          while (one.hasNext()) {
              Map data= new HashMap();
      
              data= (HashMap) one.next();
              JSONObject d = new JSONObject();
              d.putAll(data);
              String content=d.toString();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-27
        • 2015-06-12
        • 2018-06-28
        • 2013-08-14
        • 2017-09-16
        • 2012-10-26
        • 2011-06-28
        • 2012-10-06
        相关资源
        最近更新 更多