0

I have an array of jsons like this

[
    {"submitted":"Bob","limit":0,"ID":123,"target":3},
    {"submitted":"Kate","limit":500,"ID":3221,"target":2}
 ]

I need to find a way how to insert a record into that file, without overwriting the file, or loading everything into memory

currently i'm doing it like this

 try (FileWriter file = new FileWriter("C:/test/output.json", true);
         BufferedWriter bfile = new BufferedWriter(file);
         PrintWriter outFile = new PrintWriter(bfile))
    {
        outFile.write(obj.toJSONString()+System.lineSeparator());
        outFile.flush();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
2
  • Why you don't want to load all data to memory? As I see your data is very minimal. What prevents you to do? Commented Aug 28, 2018 at 18:50
  • @EmreSavcı it's just a sample; it has way more columns and rows, and I thought to make a temp solution until we get our DB ready Commented Aug 28, 2018 at 19:46

1 Answer 1

3

You can read and write json object&array using org.json as below. But I can't sure that editing a json file without reading it into memory could be possible.

package yourPackage;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) throws IOException {
        JSONArray root = new JSONArray(new String(Files.readAllBytes(Paths.get("test.json"))));

        JSONObject obj = new JSONObject();
        obj.put("submitted","");
        obj.put("limit", 0);
        obj.put("ID", 123);
        obj.put("target", 3);

        root.put(obj);

        Files.write(Paths.get("test.json"), root.toString().getBytes());
    }
}

maven dependency of org.json :

    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180130</version>
    </dependency>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.