Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从java创建JSON文件而不复制元素?_Java_Json_Duplicates - Fatal编程技术网

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

如何从java创建JSON文件而不复制元素?,java,json,duplicates,Java,Json,Duplicates,我正在尝试制作一个基于服务器-客户端套接字通信的简单字典程序。我试图将用户的单词和意思输入保存为JSON文件(这是稍后搜索的字典数据),但当我添加查询时,它最终会有重复的JSON对象 例如,如果我添加happy,然后添加weather和hello,那么用JSON文件编写的结果是 如下 {"hello":"greeting"}{"happy":"joy","hello":"greeting"} {"happy":"joy","weather":"cold","hello":"greeting"}

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

例如,如果我添加happy,然后添加weather和hello,那么用JSON文件编写的结果是 如下

{"hello":"greeting"}{"happy":"joy","hello":"greeting"} 
{"happy":"joy","weather":"cold","hello":"greeting"}` 
而不是
{“你好”:“问候”}{“快乐”:“快乐”}{“天气”:“寒冷”}
就像我想要的那样

我如何解决这个问题

这个函数的代码是

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);
...
Map dictionary=newhashmap();
字典。放(字,意思);
...

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

Map<String, String> dictionary = new HashMap<>();
dictionary.put(word, meaning);
...
Map dictionary=newhashmap();
字典。放(字,意思);
...

使用hashmap或arraymap。。它将替换以前的数据。请使用hashmap或arraymap。。它将替换您以前的数据。