如何从文件中解析JSON数组?[英] How to parse JSON array from file?

问题描述

我有来自文件的 JSON.

{  
  "from_excel":[  
    {  
      "solution":"Fisrt",
      "num":"1"
    },
    {  
      "solution":"Second",
      "num":"2"
    },
    {  
      "solution":"third",
      "num":"3"
    },
    {  
      "solution":"fourth",
      "num":"4"
    },
    {  
      "solution":"fifth",
      "num":"5"
    }
  ]
}

并且想要解析解决方案和编号列表.

使用的库 org.json.simple.*

试试这个

        Object obj = parser.parse(new FileReader("E:\\json.txt"));

        JSONObject jsonObject = (JSONObject) obj;

        out.println(jsonObject.get("from_excel"));

        JSONObject obj_new = (JSONObject) jsonObject.get("from_excel");

        JSONArray solution = (JSONArray) obj_new.get("solution");

        Iterator iterator = solution.iterator();
        while (iterator.hasNext()) {
            out.println(iterator.next());
        }

我做错了什么?

如果尝试写


JSONObject solutions = (JSONArray) jsonObject.get("from_excel");

在此处输入图片描述

如果尝试写


JSONArray array = obj.getJSONArray("from_excel");

得到错误在此处输入图片描述

推荐答案

JSON 中没有"解决方案"数组."from_excel"是数组.所以你的代码应该是这样的:

Object obj = parser.parse(new FileReader("E:\\json.txt"));

    JSONObject jsonObject = (JSONObject) obj;

    out.println(jsonObject.get("from_excel"));

    JSONArray solutions = (JSONArray) jsonObject.get("from_excel");

    Iterator iterator = solutions.iterator();
    while (iterator.hasNext()) {
        out.println(iterator.next());
    }

本文地址:https://www.itbaoku.cn/post/978433.html