Search code examples
javajsonfilenewlineprintwriter

How to add newline between the 2 objects in JSON response ? And also how to remove the [ ] square brackets from the json file?


I tried using line.separator and \n as well. But its not working. Here is my code :

        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();
    }

Edit 1 Here is the updated code with the JSONObject, also adding indentfactor in the object shows com.fasterxml.jackson.core.io.JsonEOFException: Unexpected end-of-input: expected close marker for Object:

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();
    }

Solution

  • 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();