gpt4 book ai didi

java - 如何从java创建JSON文件而不重复元素?

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:23 25 4
gpt4 key购买 nike

我正在尝试制作一个基于服务器-客户端套接字通信的简单字典程序。我正在尝试将用户单词和含义输入保存为 JSON 文件(这是稍后要搜索的字典数据),但是当我添加查询时,它最终会出现重复的 JSON 对象

例如,如果我添加 happy,然后添加 Weather 和 hello,则写入 JSON 文件的结果是像下面这样

{"hello":"greeting"}{"happy":"joy","hello":"greeting"} 
{"happy":"joy","weather":"cold","hello":"greeting"}`

而不是得到{"hello":"greeting"}{"happy":"joy"}{"weather":"cold"} 就像我想要的

如何解决这个问题?

我的该函数的代码是

case "add":{
FileWriter dictionaryWriter = new FileWriter("dictionary.json",true);

//split command again into 2 part now using delimiter ","
String break2[] = msgBreak[1].split(",");
String word = break2[0];
String meaning = break2[1];

dictionary.put(word, meaning);
System.out.println("Writing... " + word+":"+meaning);
dictionaryWriter.write(dictionary.toString());
//flush remain byte
dictionaryWriter.flush();
//close writer
dictionaryWriter.close();

break;}

该函数与其他字典函数一起在 while(true) 循环中

我尝试删除附加文件部分,但是当我删除 (,true) 部分时,重复错误停止,但每当我获得新连接时,都会创建新的字典文件,而不是保存所有数据。

如果有人能帮我解决这个问题,我将不胜感激!预先感谢您。

最佳答案

您可以尝试每次都创建一个新词典,而不是使用现有的词典

Map<String, String> dictionary = new HashMap<>();
dictionary.put(word, meaning);
...

关于java - 如何从java创建JSON文件而不重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com