首页 > 解决方案 > 使用 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();
    }
} }

标签: javajsonfile

解决方案


您正在使用该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();


推荐阅读