从LinkedHashMap转换为Json String [英] Convert from LinkedHashMap to Json String
问题描述
我正在使用Jongo与Mongo合作,当我进行查询时,我收到了一个LinkedHashMap。
I'm Workin with Mongo using Jongo, when I do a query I receive a LinkedHashMap as result.
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 } content将是{user = something},它不是json只是来自HashMap的toString方法。
the problem is that if the json is {"user":"something"} content will be {user=something}, it is not a json is only toString method from HashMap.
我如何获得原始JSON?。
How I can get the original JSON?.
我没有用于映射响应的类,并且它不是创建map类的解决方案,这就是我使用Object.class的原因。
I don't have a class to map the response, and it is not a solution create a map class, that is why I use a Object.class.
推荐答案
如果您可以访问某些JSON库,那么这就好了。
If you have access to some JSON library, it seems like that's the way to go.
如果使用org.json库,请使用 public JSONObject(java.util.Map map)
:
If using org.json library, use public JSONObject(java.util.Map map)
:
String jsonString = new JSONObject(data).toString()
如果是Gson,请使用< a href =https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html#toJson%28java.lang.Object,%20java.lang .hellboy提到的.reflect.Type%29rel =noreferrer> gson.toJson()
方法:
If Gson, use the gson.toJson()
method mentioned by @hellboy:
String jsonString = new Gson().toJson(data, Map.class);
这篇关于从LinkedHashMap转换为Json String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!