Convert from LinkedHashMap to Json String

I work with Mongo using Jongo, when I make a request, I get the result of 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();
        }

the problem is that if json is {"user": "something"} content will be {user = something}, it is not json - this is just the toString method from HashMap.

How can I get the original JSON ?.

I don't have a class to map the response to, and this is not a solution creating a map class, so I use Object.class.

+4
source share
5 answers

If you have access to some JSON library, it looks like this is the way to go.

If you are using the org.json library, use public JSONObject(java.util.Map map):

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

Gson gson.toJson(), @hellboy:

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

Gson- Google, JSON. LinkedHashMap json -

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

One of the com.mongodb.BasicDBObject constructors takes the map as input. Then you just need to call toString () on the BasicDBObject.

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

I solved the problem using the following code:

    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();
    }
0
source
String content = data.toString()
.replaceAll("=", "\":\"")
.replaceAll(",", "\",\"")
.replaceAll("}", "\"}")
.replaceAll("{", "{\"");
0
source

Source: https://habr.com/ru/post/1535082/


All Articles