java - 使用 GSON 从对象转换为字符串时添加了不需要的字符

标签 java arrays json gson

我正在使用 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/

相关文章:

java - 向上转换对静态方法有影响吗?

java - P5 : Remove TableRows containing Null/NaN

javascript - 使用 json.js 字符串化多维数组的问题

java - 我在 Android JSON 解析从 URL 检索时遇到错误

java - 在获得 Volley 响应时始终获得 "please check the number"

java - 使用不同的设置重复运行 JUnit 测试

c++ - 为什么这不起作用 : `int arr[size]` but this does `int* arr = new int[size]` ?

javascript - 如何根据表单的文本输入准备值列表?

c - 内部有其他结构数组的结构的可用内存 - C

java - Java将字符串转为float