我使用MySQL
从JDBC
检索了一些数据,我想将所有数据存储在JSONArray
中并将其写入文件。有人能帮助我吗?
我收到了以下错误:
"Exception in thread "main" org.json.JSONException: A JSONArray text must
start with '[' at 1 [character 2 line 1]"
在代码中:
String sql = "SELECT * FROM quizQuestionAnswerGeneral, quizAnswerGeneral, quizQuestionGeneral "
+ "WHERE quizQuestionAnswerGeneral.idQuestion = quizQuestionGeneral.id "
+ "AND quizQuestionAnswerGeneral.idAnswer = quizAnswerGeneral.idAnswer;";
preparedStatement = connection.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery(sql);
while (rs.next()) {
String id = rs.getString("id");
String idQuestion = rs.getString("idQuestion");
String answerText = rs.getString("answerText");
String correct = rs.getString("correct");
String questionText = rs.getString("questionText");
System.out.println("id: " + id);
System.out.println("idQuestion: " + idQuestion);
System.out.println("answerText: " + answerText);
System.out.println("correct: " + correct);
System.out.println("questionText: " + questionText);
System.out.println("*----------------------------------------*");
JsonObject obj = Json.createObjectBuilder()
.add("id", id)
.add("idQuestion", idQuestion)
.add("answerText", answerText)
.add("correct", correct)
.add("questionText", questionText)
.build();
String jArray = obj.toString();
JSONArray jsonArray = new JSONArray(jArray);
FileWriter file = new FileWriter("C:\\Users\\i5\\Desktop\\Json.txt");
while (jsonArray.iterator().hasNext()) {
file.write(jsonArray.toString());
}
System.out.println("Succes!");
file.flush();
file.close();
答案 0 :(得分:0)
似乎你混合了不同的Json库,因为你有JSONArray而不是JsonArray。 请尝试以下方法:
JsonArray jsonArray = Json.createArrayBuilder()
.add(obj)
.build();
答案 1 :(得分:0)
您应该在第一个循环之外创建JSONArray对象,并使用ResultSet中的每一行为循环中的值填充它。
答案 2 :(得分:0)
我认为你应该选择一些简单的东西:
现在你正试图在while循环中创建一堆json数组。正确的方法是创建一堆JsonObject,然后在while循环之后将它们添加到JsonArray。