java - 使用 java 读取 JSON 文件
问题描述
我在使用 Java 从 JSON 文件中读取“电子邮件”字段时遇到问题。当我尝试阅读它时,它只阅读第一个,即使我放了多个,我尝试了不同的东西,但似乎什么也没有。有什么办法解决吗?这是代码:
这是登录方法,我将有关客户的所有数据写入 JSON 文件
JSONObject customer = new JSONObject();
JSONArray list = new JSONArray();
customer.put("Email", emailCliente.getText());
customer.put("Tipo", "Cliente");
customer.put("Name", nomeCliente.getText());
customer.put("Surname", cognomeCliente.getText());
customer.put("BirthDate", dataNascitaCliente.getText());
customer.put("Address", indirizzoCliente.getText());
customer.put("Phone", telefonoCliente.getText());
customer.put("Password", pswCliente.getText());
list.add(customer);
try {
FileOutputStream file = new FileOutputStream("Db.json", true);
ObjectOutputStream fileWriter = new ObjectOutputStream(file);
fileWriter.writeObject(list);
fileWriter.flush();
fileWriter.close();
}
这是从 JSON 文件中读取的代码:
public class Read implements Serializable{
public static void main(String[] args) throws IOException {
try{
FileInputStream reader = new FileInputStream("Db.json");
ObjectInputStream ois = new ObjectInputStream(reader);
Object customer = (Object) ois.readObject();
JSONArray tmp = (JSONArray) (customer);
for(Object obj : tmp) {
JSONObject tmpObj = (JSONObject) obj;
System.out.println(tmpObj.get("Email"));
}
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} }
解决方案
您正在使用该org.json
库来创建和读取 JSON 数据。
不。那个图书馆很糟糕。
我知道json.org
列出它。
一个很好的选择是jackson ,或者如果你想要一个替代品,也许是gson 。正如@Raúl Garcia 在评论中提到的,这里是关于 jackson 的一个很好的 baeldung 教程。
注意:DataInputStream
并且DataOutputStream
适用于 java 的序列化机制,它不是 JSON,而且您在任何情况下都不想要这些,因此,按照教程,扔掉您的“读取”代码并从头开始。此外,您的异常代码有问题;异常包含 4 位信息(类型、消息、跟踪和原因);您丢弃了 4 条有用信息中的 3 条,然后盲目地继续,这可能会在您的日志中产生更多混乱,从而极难找出问题所在。停止这样做;只是“抛出”这样的异常。如果您真的真的不能,请修复您的 IDE 以生成catch (Foo e) {throw new RuntimeException(e);}
默认的 catch 块。从不 e.printStackTrace();
。
推荐阅读
- python - 基于时间戳列加入两个dfs
- android - 将协程与 RxJava 和 Moshi 一起使用不起作用
- php - 使用 PHP Curl 插入数据
- javascript - 量角器元素未附加到页面文档
- node.js - 笑话 + 模拟实现 + 调用次数:0
- c# - 机器中的多任务与多进程
- reactjs - 日期选择器 npm 在本机反应中不起作用
- node.js - Svelte/Sapper - 遇到与 Luxon 和 Lodash 相关的构建错误
- android-fragments - 尝试在 kotlin 的片段中执行自动图像滑块,但是 runouithread 不起作用。任何可能的解决方案?
- java - 浏览器和邮递员返回结果,但由于 %26,Rest 模板返回 0 个结果