繁体   English   中英

用java读取JSON文件

[英]Reading a JSON file with java

我在使用 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 教程

注意: DataInputStreamDataOutputStream用于 Java 的序列化机制,它不是 JSON,在任何情况下您都不需要它们,因此,按照教程,扔掉您的“读取”代码并从头开始。 此外,您的异常代码有问题; 异常包含 4 位信息(类型、消息、跟踪和原因); 您丢弃了 4 个有用的信息中的 3 个,然后盲目地继续,这可能会在您的日志中产生更多的混乱,使得尝试找出问题所在变得极其困难。 停止这样做; 只是“抛出”这样的异常。 如果你真的,真的不能,修复你的 IDE 以生成catch (Foo e) {throw new RuntimeException(e);}作为默认的 catch 块。 永远不要e.printStackTrace(); .

当您使用 unify-jdocs 时,您可以像这样阅读一行:

Document d = new JDocument(s); // where s is a JSON string
String s = d.getString("$.Email");

unify-jdocs 是我创建的用于处理 JSON 文档的库。 它还提供了许多其他功能。 https://github.com/americanexpress/unify-jdocs上查看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM