从LinkedHashMap转换为Json String

时间:2014-04-04 18:38:46

标签: java json mongodb linkedhashmap

我正在使用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只是来自HashMap的toString方法。

我如何获得原始JSON?。

我没有用于映射响应的类,并且它不是创建map类的解决方案,这就是我使用Object.class的原因。

5 个答案:

答案 0 :(得分:16)

如果您可以访问某些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);

答案 1 :(得分:5)

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

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

答案 2 :(得分: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();
    }

答案 3 :(得分:0)

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

    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();
    }

答案 4 :(得分:-1)

QModelIndex