[英]How to Parse a JAVA ArrayList from a JSON file
我已經編寫了以下代碼,將包含多個其他對象的復雜Java對象作為文件存儲在磁盤上
public static void savePattern(ArrayList<Pattern> p,String filename){
String fn;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(p, new TypeToken<ArrayList<Pattern>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String json = gson.toJson(jsonArray);
try {
//write converted json data to a file named "file.json"
if(filename != null){
fn = "JsonObjects/objects.json";
}
else{
fn = "JsonObjects/" + filename + ".json";
}
FileWriter writer = new FileWriter("fn");
writer.write(json);
writer.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
當我嘗試編寫將文件從磁盤加載到具有該類型的ArrayList的方法時,我完全陷入困境。
public static ArrayList<Pattern> loadPattern(){
ArrayList<Pattern> patterns = new ArrayList<>();
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
try {
BufferedReader br = new BufferedReader(new FileReader("JsonObjects/objects.json"));
JsonObject jo = (JsonObject)jsonParser.parse(br);
} catch (IOException e) {
e.printStackTrace();
}
return patterns;
}
你有沒有嘗試過:
public static List<Pattern> loadPattern(){
ArrayList<Pattern> patterns = new ArrayList<>();
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
try {
BufferedReader br = new BufferedReader(new FileReader("JsonObjects/objects.json"));
JsonElement jsonElement = jsonParser.parse(br);
//Create generic type
Type type = new TypeToken<List<Pattern>>() {}.getType();
return gson.fromJson(jsonElement, type);
} catch (IOException e) {
e.printStackTrace();
}
return patterns;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.