如何在JSON响应的2个对象之间添加换行符?还有如何从json文件中删除[]方括号? [关闭]

问题描述 投票:0回答:1

我也尝试使用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();
    }
java json file newline printwriter
1个回答
1
投票
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();
© www.soinside.com 2019 - 2024. All rights reserved.