【问题标题】:Do I need to care about type of encoding if the JSON file is going to share across different platforms如果 JSON 文件要跨不同平台共享,我是否需要关心编码类型
【发布时间】:2013-06-07 06:08:34
【问题描述】:

目前,我使用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;
}

【问题讨论】:

    标签: java android encoding gson


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 2020-01-17
      • 1970-01-01
      相关资源
      最近更新 更多