如何解析文件中的JSON数组?

时间:2016-09-25 17:03:31

标签: java json

我有来自档案的JSON。

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

并希望解析Solution和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");

enter image description here

如果试着写


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

得到错误 enter image description here

3 个答案:

答案 0 :(得分:3)

工作解决方案

JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {

    jsonObject = (JSONObject) parser.parse(new FileReader("E:\\json.txt"));

    out.println("<br>"+jsonObject);


    JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
    // for row output 1
    for(Object o: from_excel){
        out.println("<br>"+o);
    }
    // for row output 2
    Iterator iterator = from_excel.iterator();
    while (iterator.hasNext()) {
        out.println("<br>"+iterator.next());
    }
    // for item output 3
    for (int i = 0; i < from_excel.size(); i++) {

        JSONObject jsonObjectRow = (JSONObject) from_excel.get(i);
        String num = (String) jsonObjectRow.get("num");
        String solution = (String) jsonObjectRow.get("solution");
        out.println("<br>num="+num+"; solution="+solution);
    }
} catch (Exception e) {
    out.println("Error: "+e);
}

答案 1 :(得分:2)

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

答案 2 :(得分:0)

from_excel是JSON数组而不是对象。所以你应该实现它是数组。

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

然后迭代数组并获取每个jsonobject。像下面的东西

for(int i = 0 ; i < array.length() ; i++){
    array.getJSONObject(i).getString("solution");
}
相关问题