Java toJson(Gson)

时间:2018-02-26 09:06:44

标签: java json gson

我试图将我的套牌对象保存在我的Json文件中,我使用的是gson.toJson(obj,新的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();
    }

谢谢;)

0 个答案:

没有答案