如何从 gson 生成的字符串中转义或删除“\”?

sam*_*sam 4 java string json gson

我从属性文件加载一个值,然后将其传递给 gson 方法以将其转换为最终的 json 对象。但是,来自属性文件的值带有双引号,gson 会在输出中添加“\”。我已经浏览了整个网络但无法找到解决方案

属性文件包含

0110= This is a test for the renewal and the "Renewal no:" 
Run Code Online (Sandbox Code Playgroud)

这是我的代码

public String toJSONString(Object object) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    //Note object here is the value from the property file
    return gson.toJson(object);
}
Run Code Online (Sandbox Code Playgroud)

这会产生

"{ResponseCode:0110,ResponseText:This is a test for the renewal and the \"Renewal no:\"}"
Run Code Online (Sandbox Code Playgroud)

我不确定在输出中,为什么它在文字周围添加或包裹 \ ,或者属性文件值中的双引号在哪里?

Sot*_*lis 5

根据对您问题的评论,该参数实际上引用了具有以下值的objectJavaString

{ResponseCode:0110,ResponseText:This is a test for the renewal and the "Renewal no:"}
Run Code Online (Sandbox Code Playgroud)

我不能说为什么,但这就是你的String内容。

StringGson是一种解释为 JSON 字符串的特殊类型。由于"是必须在 JSON 字符串中转义的特殊字符,因此它Gson会生成 JSON 字符串。

"{ResponseCode:0110,ResponseText:This is a test for the renewal and the \"Renewal no:\"}"
Run Code Online (Sandbox Code Playgroud)