简体   繁体   中英

Convert Map to String with double quotes escaped using Gson

I have the following Map :

import java.util.Map;

Map<String, Object> myMap = Map.of(
    "key1", "value1",
    "key2", Map.of(
        "key2-1", "value2-1",
        "key2-2", 22
    )
));

I'm trying to convert this to the following String using Gson :

String expected = // ???
System.out.println(expected);
{\"key1\":\"value1\",\"key2\":{\"key2-1\":\"value2-1\",\"key2-2\":22}}

(note that double quotes when printing are escaped).

As of now, to achieve this, I'm doing:

import com.google.gson.Gson;

String myMapAsJsonString = new Gson().toJson(myMap);
String myMapAsJsonStringWithDoubleQuotesEscaped = myMapAsJsonString.replace("\"", "\\\"");

But I'm pretty sure the second line can be replaced by something else, and that I can only use Gson to achieve the escaping I want?

Any idea would be greatly appreciated !

(Thanks to @fluffy )

Instead of doing:

String myMapAsJsonStringWithDoubleQuotesEscaped = myMapAsJsonString.replace("\"", "\\\"");

I've just reserialized the JSON string once again:

import com.google.gson.Gson;

String myMapAsJsonString = new Gson().toJson(myMap);
// reserialize once again with toJson method
String myMapAsJsonStringWithDoubleQuotesEscaped = new Gson().toJson(myMapAsJsonString);

And got the correct result I was expecting:

System.out.println(myMapAsJsonStringWithDoubleQuotesEscaped);

prints:

"{\"key1\":\"value1\",\"key2\":{\"key2-1\":\"value2-1\",\"key2-2\":22}}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM