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



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

属性文件包含

0110= This is a test for the renewal and the "Renewal no:" 

这是我的代码

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);
}

这会产生

"{ResponseCode:0110,ResponseText:This is a test for the renewal and the "Renewal no:"}"

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

根据对您的问题的评论,object参数实际上是引用具有以下值的 JavaString

{ResponseCode:0110,ResponseText:This is a test for the renewal and the "Renewal no:"}

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

String是一种特殊类型,Gson解释为 JSON 字符串。由于"是必须在 JSON 字符串中转义的特殊字符,因此这就是Gson执行并生成 JSON 字符串的作用。

"{ResponseCode:0110,ResponseText:This is a test for the renewal and the "Renewal no:"}"

\ 字符正在转义字符串中的 " 等特殊字符。不能在没有前导的字符串中存储 " 。它必须是\"。

显示任何输出字符串时,可以删除斜杠。

Apache Commons有一个用于处理转义和取消转义字符串的库:https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

最新更新