【问题标题】:How to input a JSON byteCode (txt file) and parse it?如何输入 JSON 字节码(txt 文件)并解析?
【发布时间】:2017-01-31 02:55:25
【问题描述】:

我制作了一个 JSON 文件,并使用 FileOutputStream 将它作为文本文件保存在我的硬盘中。然后我使用 FileinputStream 将文件输入到一个单独的类中。我使用此代码打印 JSON,但我现在如何使用 JSONParser 解析它。

 public static void main(String[] args) throws Exception {
    FileInputStream fileInputStream = new FileInputStream("D:\\XmlToJson.txt");
    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
    JSONArray jsonArray = (JSONArray) objectInputStream.readObject();

【问题讨论】:

  • 虽然你可以猜到这里的编程语言是Java,但如果你添加一个标签来说明语言会很好。

标签: json input inputstream


【解决方案1】:

ObjectInputStream 不是在这里使用的正确类。也就是从Java自己的序列化方案中读取Java对象。与 JSON 无关。为什么JSONParser 如果您不想解析惰性并使用解析事件来构建除JSONArray 之外的一些数据结构,那么JsonReader 是要走的路。

稍微改编自 Java 文档的示例:

public static void main(String[] args) throws Exception {
    FileInputStream fileInputStream = new FileInputStream("D:\\XmlToJson.txt");
    JsonReader jsonReader = Json.createReader(fileInputStream);
    JsonArray array = jsonReader.readArray();
    jsonReader.close();
    // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    相关资源
    最近更新 更多