[英]Java toJson (Gson)
我正在嘗試將我的卡組對象保存在我的Json文件中,正在使用gson.toJson(obj,new FileWriter(“ D:\\ file.json”))); 但是當我運行代碼時,它會擦除我的所有json文件。 有我的代碼:
Gson gson = new Gson();
String res = JsonTransform.readFromFile("/json.json", true);
Deck newDeck = gson.fromJson(res, Deck.class);
System.out.println(newDeck);
System.out.println("Do you want to add question ? enter 1 for yes and 2 for no");
answer = sc.nextInt();
sc.nextLine();
while(answer==1) {
System.out.println("Please enter the author");
author=sc.nextLine();
System.out.println("Please enter the category");
category=sc.nextLine();
System.out.println("Please enter the statement");
statement=sc.nextLine();
System.out.println("Please enter the answer");
answ=sc.nextLine();
Question q = new Question(author,category,statement,answ);
newDeck.createQuestion(q);
System.out.println("Do you want to add again a new Question ? enter 1 for yes and 2 for no");
answer=sc.nextInt();
}
try {
System.out.println(newDeck);
gson.toJson(newDeck, new FileWriter("C:\\Users\\flori\\workspace\\Projet_Q2\\src\\json.json"));
} catch (JsonIOException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
謝謝 ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.