我做了一个简单的问卷。我需要把答案写在一个JSON文件中。怎么做呢?我使用IDEA Intellij和库GSON来处理JSON。这是主类“测验”:
package questions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Scanner;
public class Quiz {
public static <Outfile> void main(String[] args) throws IOException {
String userJson = "[{\"question\": \"1.What is your marital status?\", \"a\": \"(a)Single\", \"b\": \"(b)Married\"}," +
"{\"question\": \"2.Are you planning on getting married next year?\", \"a\": \"(a)Yes\", \"b\": \"(b)No\"},"+
"{\"question\": \"3.How long have you been married?\", \"a\": \"(a)Less than a year\", \"b\": \"(b)More than a year\"},"+
"{\"question\": \"4.Have you celebrated your one year anniversary?\", \"a\": \"(a)Yes\" , \"b\": \"(b)No\"}]";
Gson gson = new Gson();
Type questionListType = new TypeToken<ArrayList<Question>>(){}.getType();
ArrayList<Question> questionArray = gson.fromJson(userJson, questionListType);
FileWriter fileWriter = new FileWriter("answer.json");
for(Question question : questionArray) {
System.out.println("Question:" + question.question);
System.out.println("Answer:" + question.a + " " + question.b);
Scanner keyboardInput = new Scanner(System.in);
String answer = keyboardInput.nextLine();
System.out.println("You got: " + answer);
}
}}
这是课堂“问题”:
package questions;
public class Question {
public String question;
public String a;
public String b;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setAnswer2(String b) {
this.b = b;
}
}
我正在尝试使用FileWriter,但是我做错了。输出文件是空的。请帮助我。
2条答案
按热度按时间vptzau2j1#
您已经创建了一个FileWriter,但实际上从未向该文件写入任何内容。这就是该文件为空的原因。
这将允许您将内容写入文件。请确保在写入内容后在FileWriter上调用
close()
。之后,您的文件answer.json
应包含:gzszwxb42#