我也尝试使用line.separator和\ n。但是它不起作用。这是我的代码:
ResultSetMetaData rsmd = rs.getMetaData();
JSONArray json = new JSONArray();
while (rs.next()) {
int numColumns = rsmd.getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 1; i <= numColumns; i++) {
String column_name = rsmd.getColumnName(i);
obj.put(column_name, rs.getObject(column_name));
}
json.put(obj);
}
PrintWriter file = new PrintWriter("JFile.json");
file.println(json);
file.close();
} catch (SQLException | FileNotFoundException e) {
e.printStackTrace();
}
编辑1这是使用JSONObject更新的代码,还在对象中添加了indentfactor显示com.fasterxml.jackson.core.io.JsonEOFException:意外的输入结束:预期的对象关闭标记:
ResultSetMetaData rsmd = rs.getMetaData();
JSONObject obj = new JSONObject();
while (rs.next()) {
int numColumns = rsmd.getColumnCount();
for (int i = 1; i <= numColumns; i++) {
String column_name = rsmd.getColumnName(i);
obj.put(column_name, rs.getObject(column_name));
}
}
PrintWriter file = new PrintWriter("downloads/JSONFile.json");
file.println(obj.toString());
file.close();
} catch (SQLException | FileNotFoundException e) {
e.printStackTrace();
}
ResultSetMetaData rsmd = rs.getMetaData();
JSONArray jsonArr = new JSONArray();
while (rs.next()) {
int numColumns = rsmd.getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 1; i <= numColumns; i++) {
String column_name = rsmd.getColumnName(i);
obj.put(column_name, rs.getObject(column_name));
}
jsonArr.put(obj);
}
//add this JSONArray to another JSONObject
JSONObject rootJSONObject = new JSONObject();
rootJSONObject.put("data",jsonArr);
PrintWriter printWriter = new PrintWriter("sample.json");
printWriter.write(rootJSONObject.toString(4).replace("{", "\n{\n").replace("}", "\n}\n"));
printWriter.close();