2016-09-25 7 views
0

私はファイルからJSONを持っています。ファイルから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 libに使用さ

。*

はこの1

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

は私が間違って何をやってみては?

 

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

のgetエラー enter image description here

答えて

1

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

解決策はlib" org.json.simple。* "私は互換性のない型でエラーを試します。 –

+0

@Neerajはこれを 'org.json.simple'で動作させます –

0

from_excelを書き込もうとした場合

 

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

enter image description here

を書き込もうとした場合には、JSON配列でないオブジェクトです。だからあなたはそれが配列であるべきだ。

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

次に、配列を繰り返して各jsonオブジェクトを取得します。以下のようなもの

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

そのソリューションのlibに取り組ん必見 "org.json.simple *。" を?私は試して、エラーを取得する方法を解決できません(問題の本体にエラーがある画像を追加してください) –

+0

@SpringLearnerはこれを 'org.json.simple'で動作させます –

2

作業溶液

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