2012-02-12 22 views
0

多くのデバイスの構成情報を含むファイルシステム内のファイルを反復しようとしています。json-simple、ファイルからの読み取り

ファイルは、この形式である:

{ 
    "myDevicesInfo": 
    [ 
     { 
      "DeviceType":"foo", 
      "DeviceName":"foo1", 
      "IPAddress":"192.168.1.1", 
      "UserName":"admin", 
      "Password":"pw" 
     } 
    ] 
} 

内側のキーと値のペアを取得しようとしたとき、私は、次のエラーを取得しています:

例外をスレッド「メイン」Javaで.lang.ClassCastException:org.json.simple.JSONArrayをorg.json.simple.JSONObjectにキャストすることはできません mav2bac.loadDevices(bac.java:98) at mav2bac.main(bac.java:70)

File appBase = new File("."); //current directory 
      String path = appBase.getAbsolutePath(); 
      System.out.println(path); 

      Object obj = parser.parse(new FileReader("bac.yml")); 

      JSONObject jsonObject = (JSONObject) obj; 
      JSONObject jsonObjectDevice = (JSONObject)jsonObject; 
      JSONObject deviceAttributes = (JSONObject) jsonObject.get("myDevicesInfo"); 

      Map json = (Map)parser.parse(jsonObject.toJSONString(), containerFactory); 
      System.out.println(json.values()); 
      Iterator iter = json.entrySet().iterator(); 
      System.out.println("==iterate result=="); 
      while(iter.hasNext()){ 
       Map.Entry entry = (Map.Entry)iter.next(); 
       //System.out.println(entry.getKey() + "=>" + entry.getValue()); 
       System.out.println(entry.getValue()); 
      } 

ので使用ContainerFactoryを変換取得し、これらの値を含むオブジェクトをインスタンス化する適切な方法は何ですか?


答えて

3

問題はmyDevicesInfoはJSONオブジェクトの配列ではなくJSONオブジェクトであるということです。その次の行:

JSONObject deviceAttributes = (JSONObject) jsonObject.get("myDevicesInfo"); 

ニーズを試してみてください

JSONArray deviceAttributes = (JSONArray) jsonObject.get("myDevicesInfo"); 
+0

ペア? – bentaisan

+0

JSONArrayはJavaのListで、リストを反復するのと同じ方法で繰り返し処理できます。 – 271828183

+0

これは私が得る出力です:myDevicesInfo = [{DeviceType = bac、DeviceName = bac、IPAddress = 192.168.1.1、UserName = admins、Password = pw}]。私は大括弧で値を取得したい。 – bentaisan

2

に変更するには、この:エラーで手伝って、今、どのように私は、キーの値を取得します

JSONParser parser = new JSONParser(); 
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(pathToJsonFile)); 
JSONArray features = (JSONArray) jsonObject.get("myDevicesInfo"); 
Iterator itr=features.iterator(); 

while(itr.hasNext()){ 
    JSONObject featureJsonObj = (JSONObject)itr.next(); 
    String deviceType = (String)featureJsonObj.get("DeviceType"); 
    String deviceName = (String) featureJsonObj.get("DeviceName"); 
    String ipadd = (String) featureJsonObj.get("IPAddress"); 
    String uname = (String) featureJsonObj.get("UserName"); 
    String pwd = (String) featureJsonObj.get("Password");      
} 
+0

これはどのライブラリですか? JSONParserはデフォルトのorg.jsonライブラリにありません –

関連する問題