使用GSON从对象转换为字符串

时间:2016-06-19 05:09:05

标签: java arrays json gson

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

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"*/

        ]

由于我需要数组中每个元素的确切长度,我需要删除添加的字符,有人可以帮我吗?

1 个答案:

答案 0 :(得分:3)

看来,你传递了一个已经JSON-ed到generateJSONFile()的字符串数组。所以他们已经包含了引文。然后generateJSONFile将它们视为数据字符串,因此转义引号。

所以你在JSON问题上有JSON。