[英]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. 我目前已经开始一个日记项目,以自学如何用Java编写代码。 The project has a graphical interface which I realized with JavaFX. 该项目具有我使用JavaFX实现的图形界面。
I want to write data into a JSON file, which I enter into two text fields and a slider. 我想将数据写入JSON文件,然后将其输入两个文本字段和一个滑块。 Such a JSON entry should look like this: 这样的JSON条目应如下所示:
{
"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. 我已经创建了一个类,可以通过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: JSONWriter的代码如下所示:
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. 稍后,我想按日期过滤来自Json文件的数据,并将包含的对象(文本字段1,textfiel2,滑块)转移到相应的字段中。
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. 这意味着,如果日期条目已经存在,并且我想更改条目中的某些内容,则应在JSON文件中将其替换,以便稍后再检索。
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. 您可以先没有JsonParser
和JsonWriter
然后使用Gson的fromJson(..)
和toJson(..)
因为您当前的Json格式很容易映射为条目POJO的映射。
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. 对于大量数据,使用JsonParser
和JsonWriter
创建一些复杂的实现可能会更有效,但是在这一点上,您应该已经研究了如何持久存储到db。
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. POJO易于操作,以后可以很容易地持久化到db中-例如,如果您决定使用仅带有少量注释的JPA
技术。
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: 这应该导致test.json.out.json
类似:
{
"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: 首先,我建议您在Web应用程序甚至台式机应用程序中使用这种通用架构,以独立于后端服务器获得前端层:
Front-end (use Java Fx if you want). 前端(如果需要,请使用Java Fx)。 Tutorial: http://www.mastertheboss.com/jboss-frameworks/resteasy/rest-services-using-javafx-tutorial 教程: http : //www.mastertheboss.com/jboss-frameworks/resteasy/rest-services-using-javafx-tutorial
Back-end (Java 1.8, Springboot, MySQL database). 后端(Java 1.8,Springboot,MySQL数据库)。 Example: there are tons of examples and tutorials using this stack, I recommend mykong or baeldung blogs. 示例:使用该堆栈有大量示例和教程,我推荐mykong或baeldung博客。
The front-end will communicate to server over HTTP request through back-end REST API using JSON or XML format for messaging. 前端将使用JSON或XML格式通过后端REST API通过HTTP请求与服务器通信。 In real life there are physically separated but just create 2 different java projects running on different ports. 在现实生活中,它们在物理上是分开的,但是只创建了两个在不同端口上运行的不同Java项目。
selected_date: Date selected_date:日期
inputs: Map of strings 输入:字符串映射
size: Integer 大小:整数
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. 您将把Java对象永久地转换为JSON字符串,我建议您使用直接执行此操作的Gson库或Jackson库,并且不需要手动构建JsonObject。 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. 如果仍然要将JSON写入文件,请使用上述库将java对象转换为字符串(这是一个以JSON格式写入对象的字符串),然后将该字符串写入文件。 But I strongly believe it will more practice if you implement database. 但是我坚信,如果您实现数据库,它将有更多实践。
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.