簡體   English   中英

如何從文件解析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"
    }
  ]
}

並想解析解決方案和數字列表。

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

得到錯誤 在此處輸入圖片說明

工作解決方案

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM