TheOriginalNickname
TheOriginalNickname

Reputation: 135

How to create json file correctly

So I have troubles with creating Json file correctly. What I have: 1. Gson libs 2. Trying to write in a Json a new user like this:

public static void writeUserBD(String name, String surname, int age) {
        //writing in a Json format

        JSONObject writeOne = new JSONObject();
        JSONArray arr = new JSONArray();

        for(int i = 0; i< arr.size() ; i++)
        {
            writeOne.put("name", name);
            writeOne.put("surname", surname);
            writeOne.put("age", new Integer(age));
            arr.add(writeOne);
            writeOne = new JSONObject();

        }
        //creating dir&file and writing in it
        try {
            File dir = new File("Test");
            dir.mkdir();
            File f = new File("Test/TestUser.json");
            if (!dir.exists()) {
                dir.mkdirs();
            } else if (!f.exists()) {
                f.createNewFile();
            }
            //here comes writing encoding problem ! ! !
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f.getAbsoluteFile(), true), Charset.forName("UTF-8")));
            try {
                bw.write(arr + " " + "\n");
            } finally {
                bw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

But if I reload my app and try to write a new one it will write a new JSONObject and my output be like :

[{}]
[{}]

In this case i cant parse my json file (for creating simple login) im getting error like "unexcpected token [[]" As I understood this happens becouse of more than 1 jsonobject in a file.

So my question is: how can I write new users data in a json file (even if app was reloaded) in right format that i can pasre than/ for example [{},{},{}]

Upvotes: 0

Views: 2437

Answers (2)

stevecross
stevecross

Reputation: 5684

The output of your code should be an empty array because you never add an element to the array. You create a new array and iterate over it. But a new array has no elements and thus the code inside the loop will never be executed. Beside of that you want to add a new user only once and hence you don't need a loop.

You should read the file first, then add the new user to it and write it back. I created a simple example for you. I didn't use GSON before, so I'm sure that there is a better way to do this, but it works nevertheless. I used the try-with-resource feature and the new IO API of Java 7 and did not handle exceptions further. So if you want to handle exceptions inside the method change the code accordingly. I didn't create the file-structure, so you should do this on your own as well.

public static void writeUserBD(final String name, final String surname, final int age) throws IOException {
    final Path jsonFile = Paths.get("Test/TestUser.json");
    final JsonArray users = new JsonArray();

    // Read all existing users
    if (Files.isRegularFile(jsonFile)) {
        try (final JsonReader r = new JsonReader(Files.newBufferedReader(jsonFile))) {
            r.beginArray();

            while (r.hasNext()) {
                final JsonObject user = new JsonObject();

                r.beginObject();
                r.nextName();
                user.addProperty("name", r.nextString());
                r.nextName();
                user.addProperty("surname", r.nextString());
                r.nextName();
                user.addProperty("age", r.nextInt());
                r.endObject();
                users.add(user);
            }

            r.endArray();
        }
    }

    // Create the new user
    final JsonObject user = new JsonObject();

    user.addProperty("name", name);
    user.addProperty("surname", surname);
    user.addProperty("age", age);
    users.add(user);

    // Write all users
    try (final BufferedWriter w =
            Files.newBufferedWriter(jsonFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
        w.write(users.toString());
    }
}

Upvotes: 0

Yampeku
Yampeku

Reputation: 593

Try

new FileOutputStream(f.getAbsoluteFile(), false) 

true parameter appends to the current file, false should create a new one

Upvotes: 1

Related Questions