简体   繁体   中英

Java | GSON | Add JSON objects to excisting JSON-File

I have currently started a kind of diary project to teach myself how to code, which I write in Java. The project has a graphical interface which I realized with JavaFX.

I want to write data into a JSON file, which I enter into two text fields and a slider. Such a JSON entry should look like this:

{
    "2019-01-13": {
        "textfield1": "test1",
        "textfield2": "test2",
        "Slider": 2
    }
}

I have already created a class in which the values can be passed and retrieved by the JSONWriter. The class looks like this:

public class Entry {
    private String date, textfield1, textfield2;
    private Integer slider;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTextfield1() {
        return textfield1;
    }

    public void setTextfield1(String textfield1) {
        this.textfield1 = textfield1;
    }

    public String getTextfield2() {
        return textfield2;
    }

    public void setTextfield2(String textfield2) {
        this.textfield2 = textfield2;
    }

    public Integer getSlider() {
        return slider;
    }

    public void setSlider(Integer slider) {
        this.slider= slider;
    }
}

The code of the JSONWriter looks like this:

void json() throws IOException {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonWriter writer = new JsonWriter(new FileWriter("test.json",true));

    JsonParser parser = new JsonParser();
    Object obj = parser.parse(new FileReader("test.json"));

    JsonObject jsonObject = (JsonObject) obj;
    System.out.println(jsonObject);

    writer.beginObject();
    writer.name(entry.getDate());
        writer.beginObject();
        writer.name("textfield1").value(entry.getTextfield1());
        writer.name("textfield2").value(entry.getTextfield2());
        writer.name("Slider").value(entry.getSlider());
        writer.endObject();
    writer.endObject();
    writer.close();
}

The date is obtained from the datepicker. Later I want to filter the data from the Json file by date and transfer the containing objects (textfield 1, textfiel2, slider) into the corresponding fields.

If possible, I would also like to try to overwrite the objects of a date. This means, if an entry of the date already exists and I want to change something in the entries, it should be replaced in the JSON file, so I can retrieve it later.

If you can recommend a better memory type for this kind of application, I am open for it. But it should also be compatible with databases later on. Later I would like to deal with databases as well.

So far I have no idea how to do this because I am still at the beginning of programming. I've been looking for posts that could cover the topic, but I haven't really found anything I understand.

You could start without JsonParser and JsonWriter and use Gson's fromJson(..) and toJson(..) because your current Json format is easily mapped as a map of entry POJOs.

Creating some complex implementation with JsonParser & JsonWriter might be more efficient for big amounts of data but in that point you already should have studied how to persist to db anyway.

POJOs are easy to manipulate and they can be later easily persisted to db - for example if you decide to use technology like JPA with only few annotations.

See below simple example:

@Test
public void test() throws IOException {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    // Your current Json seems to be a map with date string as a key
    // Create a corresponding type for gson to deserialize to
    // correct generic types
    Type type = new TypeToken<Map<String, Entry>>() {}.getType();
    // Check this file name for your environment
    String fileName = "src/test/java/org/example/diary/test.json";
    Reader reader = new FileReader(new File(fileName));
    // Read the whole diary to memory as java objects 
    Map<String, Entry> diary = gson.fromJson(reader, type);
    // Modify one field
    diary.get("2019-01-13").setTextfield1("modified field");
    // Add a new date entry
    Entry e = new Entry();
    e.setDate("2019-01-14");
    e.setScale(3);
    e.setTextfield1("Dear Diary");
    e.setTextfield1("I met a ...");
    diary.put(e.getDate(), e);
    // Store the new diary contents. Note that this one does not overwrite the
    // original file but appends ".out.json" to file name to preserver the original
    FileWriter fw = new FileWriter(new File(fileName + ".out.json"));
    gson.toJson(diary, fw);
    fw.close();
}

This should result test.json.out.json like:

{
  "2019-01-13": {
    "textfield1": "modified field",
    "textfield2": "test2",
    "Slider": 2
  },
  "2019-01-14": {
    "date": "2019-01-14",
    "textfield1": "Dear Diary",
    "textfield2": "I met a ...",
    "Slider": 3
  }
}

Note that I also made little assumption about this:

// Just in case you meant to map "Slider" in Json as "scale" 
@SerializedName("Slider")
private Integer scale;

I will give you general tips up to you to go deeper.

First of all, I recommend you this architecture that is common on web-applications or even desktop apps to get the front-end layer separately of back-end server:

The front-end will communicate to server over HTTP request through back-end REST API using JSON or XML format for messaging. In real life there are physically separated but just create 2 different java projects running on different ports.

  1. For the back-end, just follow the tutorial to get up and running a REST API server. Set up MVC pattern: Controller layer, Service layer, Repository layer, model layer, dto layers, etc. For your specific model I recommend you the following:

selected_date: Date

inputs: Map of strings

size: Integer

  1. On Front-end project with Java FX, just re-use the code you already wrote and add some CSS if you want. Use the components actions to call the back-end REST API to create, retrieve, update and delete your data from date-picker or whatever operation you want to do.

You will transform java objects into JSON strings permanently, I recommend you to use Gson library or Jackson library that do this in a direct way and it is not need to build the JsonObject manually. If you still want to write the JSON into a file, transform the java object into string (this is a string with the object written in JSON format) using the mentioned libraries, and then write the string into file. But I strongly believe it will more practice if you implement database.

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM