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