我有Map<String, String>
稍后我想使用 Gson 序列化为 JSON。该映射的某些键包含 Unicode 字符,例如 \uf177
当我尝试将这样的映射序列化为 JSON 时,就会出现问题,假设我有 Map<String, String>
包含:
"TEST_KEY" -> "\uf177"
然后,当使用 Gson 序列化时,我有:
{
"TEST_KEY": "\\uf177"
}
这不是我想要的,我希望这些 Unicode 符号在序列化时保持原样。有办法实现这一点吗?将不胜感激任何帮助,
更新
产生问题的代码:
projectI18nFileContent = commentsRemover.transform(projectI18nFileContent);
//find json map which represents translations
Matcher fullTranslationsMapMatcher = translationsMapSerializedToJsonPattern.matcher(projectI18nFileContent);
if (!fullTranslationsMapMatcher.find()) {
throw new IllegalArgumentException(format("%s \n does not contain valid translations json map", projectI18nFileContent));
}
String translationsMapSerializedToJson = fullTranslationsMapMatcher.group();
String newTranslationsMapSerializedToJson = gson.toJson(newTranslations);
//replace old json translations map with a new
return projectI18nFileContent.replace(translationsMapSerializedToJson, newTranslationsMapSerializedToJson);
这段代码专门用于更改javascript项目的i18n文件的内容,这就是unicode不应该被转义的原因(否则它只是解析不正确)
谢谢, 干杯
最佳答案
根据Json spec反斜杠必须被转义。
所以你不应该试图阻止这种情况。这是正确的行为。
关于java - 防止Gson转义Unicode符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44110274/