【问题标题】:Unwanted characters added when using GSON to convert from object to String使用 GSON 将对象转换为字符串时添加了不需要的字符
【发布时间】:2016-06-19 05:09:04
【问题描述】:

我正在使用 Google Gson 将对象数组转换为字符串数组。这是我的代码:

TestFile.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;
 }
}

main.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里面添加代码吗?我觉得最好先修复,然后再删除不需要的符号。
  • 我正在使用 Weka api 中的 JSONSaver 将文件保存为 JSON 格式 [链接] (weka.sourceforge.net/doc.dev/weka/core/converters/…),当我将文件写入 ARFF 文件时得到了相同的结果

标签: java arrays json gson


【解决方案1】:

看来,您将一个字符串数组传递给 generateJSONFile()。所以它们已经包含了引用。然后generateJSONFile 将它们视为数据字符串,因此对引号进行转义。

所以你有 JSON 中的 JSON 问题。

【讨论】:

猜你喜欢
  • 2017-01-24
  • 2021-10-04
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
相关资源
最近更新 更多