Home > Enterprise >  How to remove curly braces before writing JSON object in java
How to remove curly braces before writing JSON object in java

Time:04-25

I am trying to make a simple JSON-DB in Java since the current library on maven is horrendously overcomplicated. I have this method that takes in a key and value to put into a JSONObject and write it to my database.json file.

public static void put(String path, String key, Object[] value){
        //creates new JSONObject where data will be stored
        JSONObject jsondb = new JSONObject();

        try{
            //adds key and value to JSONObject
            jsondb.put(key, value);

        } catch (JSONException e){
            e.printStackTrace();
        } //end try-catch

        try(PrintWriter out = new PrintWriter(new FileWriter(path, true))) {
            out.write(jsondb.toString());
            out.write(',');
        } catch (Exception e){
            e.printStackTrace();
        } //end try-catch
    } //end put()

Here is my main method where I write some data to the file

public static void main(String[] args) throws Exception {

        String path = "app.json";

        Object[] amogus = {"Hello", 1, 2, 3, 4, 5};
        Object[] amogus1 = {"Hello", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

        JsonDB db = new JsonDB(path);

        db.put(path, "arr", amogus);
        db.put(path, "arr1", amogus1);

    }

What happens is that it save each data in a set of curly braces. So when I write to the file more than once like I do in my main method it saves it like this:

{"arr": ["Hello", 1, 2, 3, 4, 5]}{"arr1": ["Hello", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]}

This causes VSCode to throw an error since this isnt valid JSON. How would I make the method remove the curly braces and add commas to make the above JSON valid JSON? I cant seem to find the documentation for this library (The library is org.json on maven).

CodePudding user response:

This is a syntax issue. Your json is not valid because the json syntax want your data to be between curly braces like this:

{
    "arr": ["Hello", 1, 2, 3, 4, 5],
    "arr1": ["Hello", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
}

instead of this, which is not a valid json:

{"arr": ["Hello", 1, 2, 3, 4, 5]}
{"arr1": ["Hello", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]}

Create your data in your map object and let your json library convert (serialize) your object in a valid json.

CodePudding user response:

I solved this problem by reading all of the content in the file and appending the JSON object that I wanted to write to the file and then write it all at once.

  • Related