【发布时间】:2017-03-16 07:21:20
【问题描述】:
我正在尝试从文件中加载由 JSON 编码的对象..
我可以每次只编写内联代码,但我想将保存/加载移动到静态实用程序类,但我不想在主代码中盲目地转换回对象。
所以我现在有
public Class MyClass(){
private List<Door> doors;
private final Type type = new TypeToken<List<Door>>(){}.getType();
private void load(){
Gson gsondecoder = new Gson();
File parent = new File ("saves");
File file = new File(parent,"doors.json");
List<Door> doors= null;
if (!parent.exists())return;
if(!file.exists())return;
try {
InputStream in = new FileInputStream(file);
InputStreamReader inread = new InputStreamReader(in);
JsonReader reader = new JsonReader(inread);
doors = gsondecoder.fromJson(reader,type);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
所以我想搬到一个更像 公共类 MyClass(){
private List<Door> doors;
private final Type type = new TypeToken<List<Door>>(){}.getType();
private void load(){
File parent = new File ("saves");
File file = new File(parent,"doors.json");
List<Door> doors= null;
doors = (List<door>) Utility.load(file,type);
}
我的问题是如何在不盲目投射的情况下返回正确的课程 即只是
door = Utility.load(file,type)
我的想法是
public class Utilities {
static Gson gsonencoder = new Gson();
/**
* The objects class must much the TypeTokens underlying class.
*
* @param file
* @param object
* @param type
*/
public static void saveFile(File file, T object, TypeToken<T> type) {
try {
if (!file.exists()) file.createNewFile();
OutputStream out = new FileOutputStream(file);
String encoded = gsonencoder.toJson(object, type.getType());
out.write(encoded.getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static T loadFile(File file, TypeToken<T> type){
if(!file.exists())return null;
T object = null;
try {
InputStream in = new FileInputStream(file);
InputStreamReader inread = new InputStreamReader(in);
JsonReader reader = new JsonReader(inread);
object = gsonencoder.fromJson(reader,type.getType());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return object;
}}
但我显然在这里遗漏了如何正确使用泛型。
【问题讨论】:
-
另外......投反对票的人......谁甚至懒得评论他投反对票的原因......干得好