如何解析文件中的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解决方案=(JSONArray)obj_new.get(“解决方案”); 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()); }
工作方案
JSONParser parser = new JSONParser(); JSONObject jsonObject; try { jsonObject = (JSONObject) parser.parse(new FileReader("E:\\json.txt")); out.println("
"+jsonObject); JSONArray from_excel = (JSONArray)jsonObject.get("from_excel"); // for row output 1 for(Object o: from_excel){ out.println("
"+o); } // for row output 2 Iterator iterator = from_excel.iterator(); while (iterator.hasNext()) { out.println("
"+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("
num="+num+"; solution="+solution); } } catch (Exception e) { out.println("Error: "+e); }
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"); }