使用Java进行json的读取于写入

使用Java进行json的读取于写入

曦暮流年 Lv4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
String readJson(String Cf) {
String json = null;
try {
FileReader f = new FileReader(Cf);
Reader reader = new InputStreamReader(new FileInputStream(Cf));
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
f.close();
reader.close();
json = sb.toString();
} catch (IOException e) {
System.out.println("读取信息失败");
}
return json;
}

总体意思就是传入一个字符串,这个值就是你的json文件的路径(可以是相对也可以是绝对),传入之后经过一系列操作最终返回json格式的字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Map<String, List<泛型>> map = JSON.parseObject(new IOJson().readJson("文件.json"), new TypeReference<Map<String, List<泛型>>>() {
});
for (Map.Entry<String, List<泛型>> entry : map.entrySet()) {
if (entry.getKey().equals(键)) {
entry.getValue().add(值);
}
}
String json = JSON.toJSONString(map);

try {
File upData = new File(文件.json);
upData.createNewFile();
Writer write = new OutputStreamWriter(new FileOutputStream("文件.json"), "UTF-8");
write.write(json);
write.flush();
write.close();
System.out.println("写入成功");
} catch (IOException e) {
System.out.println("写入失败");
}
}

这个就是先把json文件给转换成正常的Map集合,然后在使用循环找到自己要找的位置,在这个entry.getValue().add(值)进行增加增加上的集合在进行序列化再次转化成json格式,然后再把全部的字符赋值到文件里面

这样有一个好处就是增加的数据不会覆盖掉原来的数据,会在原有的基础上增加这就非常的舒服

  • 标题: 使用Java进行json的读取于写入
  • 作者: 曦暮流年
  • 创建于 : 2023-06-27 23:36:32
  • 更新于 : 2023-06-27 23:36:32
  • 链接: https://www.ximuliunian.top/2023/06/27/java/使用Java进行json的读取于写入/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
使用Java进行json的读取于写入