使用 Gson 转义双引号将 Map 转换为 String

Convert Map to String with double quotes escaped using Gson

我有以下 Map :

import java.util.Map;

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

我正在尝试使用 Gson 将其转换为以下 String :

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

(注意打印时双引号被转义了)

截至目前,为了实现这一点,我正在做:

import com.google.gson.Gson;

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

但我很确定第二行可以换成别的东西,我只能用Gson来实现我想要的转义?

任何想法将不胜感激!

(感谢@fluffy

而不是:

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

我刚刚重新序列化了 JSON 字符串:

import com.google.gson.Gson;

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

得到了我期望的正确结果:

System.out.println(myMapAsJsonStringWithDoubleQuotesEscaped);

打印:

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