Java 使用 Gson 将 Map 转换为 JSON 字符串并替换双引号
您可以使用以下代码将 goodsParamMap 转换为 JSON 字符串,并进行相应的替换操作:
import com.google.gson.Gson;
// 将 goodsParamMap 转换为 JSON 字符串
String json = new Gson().toJson(goodsParamMap);
// 替换所有的 '\"' 为 ''
json = json.replaceAll("\\\"", "");
// 找到第三个 '\"' 并替换为 ''
int count = 0;
int index = -1;
while ((index = json.indexOf('"', index + 1)) != -1) {
count++;
if (count == 3) {
json = json.substring(0, index) + json.substring(index + 1);
break;
}
}
// 找到最后一个个 '\"' 并替换为 ''
int lastIndex = json.lastIndexOf('"');
if (lastIndex != -1) {
json = json.substring(0, lastIndex) + json.substring(lastIndex + 1);
}
请注意,上述代码中使用了 Google 的 Gson 库来将 Java 对象转换为 JSON 字符串。如果您没有使用 Gson 库,可以使用其他 JSON 库进行转换。另外,为了替换 '"' 字符,需要使用双反斜杠 '\' 进行转义。
原文地址: https://www.cveoy.top/t/topic/pgF2 著作权归作者所有。请勿转载和采集!