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

查看:103
本文介绍了如何解析文件中的JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自档案的JSON。

I have JSON from file.

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

并且想要解析解决方案和Num的列表。

and want to parse list of Solution and Num.

使用了lib 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");

获取错误

get error

推荐答案

JSON中没有解决方案数组。 from_excel是数组。所以你的代码应如下所示:

There is no "solution" array in the JSON. "from_excel" is the array. So your code should look like this :

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());
    }

这篇关于如何解析文件中的JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆