我正在使用 Google Gson 将对象数组转换为字符串数组。这是我的代码:
测试文件.java
public class TestFile {
public String[] StringtoJSon(Object[] obj) {
Gson gson = new Gson();
String[] converted = new String[obj.length];
for (int i = 0; i < obj.length; i++) {
converted[i] = gson.toJson(obj[i]);
}
return converted;
}
}
主.java
TestFile tf = new TestFile();
Object[] obj = {"tt",1, "yyom"};
String[] convObj = tf.StringtoJSon(obj);
generateJSONFile(convObj);// this is class that generate a file in JSON format
所以在生成的文件中我发现“\\”被添加到数组中的每个字符串元素
例子:
"sparse" : false,
"weight" : 1.0,
"values" : [
"'\\\"tt\\\"'",
"4", /*the length of the first element "tt"*/
"1",
"1", /*the length of the second element 1 */
"'\\\"yyom\\\"'",
"6", /*the length of the last element "yyom"*/
]
因为我需要数组中每个元素的确切长度,所以我需要删除添加的字符,有人可以帮我吗?
最佳答案
看起来,您将一个字符串数组传递给 generateJSONFile()
,该数组已经 JSON-ed。因此它们已经包含了引文。然后 generateJSONFile
将它们视为数据字符串并因此转义引号。
所以你有 JSON 中的 JSON 问题。
关于java - 使用 GSON 从对象转换为字符串时添加了不需要的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37904126/