3

目前,我正在使用gson, 对对象执行序列化。它在单一平台(Windows)中工作得很好。

但是,如果我要跨不同平台(Windows、Linux、Mac、Android)共享 json 文件,是否需要使用特定类型的编码(UTF-8)?(json文件中会有外文字符)?或者,BufferedWriter/BufferedReader 使用的默认编码在所有平台上都相同?

public static boolean write(A a, File file) {
    final Gson gson = new Gson();
    String string = gson.toJson(a); 

    try {
        //If the constructor throws an exception, the finally block will NOT execute
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        try {
            writer.write(string);
        } finally {
            //no need to check for null
            //any exceptions thrown here will be caught by 
            //the outer catch block
            writer.close();
        }
    } catch (IOException ex){
        return false;
    }
    return true;
}

public static A load(File file) {
    // Copy n paste from newInstance.
    final Gson gson = new Gson();

    try {
        //If the constructor throws an exception, the finally block will NOT execute
        BufferedReader reader = new BufferedReader(new FileReader(file));
        try {
            return gson.fromJson(reader, A.class);
        } finally {
            //no need to check for null
            //any exceptions thrown here will be caught by 
            //the outer catch block
            reader.close();
        }
    } catch (IOException ex){
    }
    return null;
}
4

1 回答 1

1

补充一点,FileReader 和 FileWriter 是特定于平台的。更喜欢 ObjectStreams。同样,我的分数不允许我将其作为评论:(

于 2013-06-07T06:14:12.723 回答