2012-02-12 6 views
0

수많은 장치에 대한 구성 정보가 들어있는 파일 시스템에서 파일을 반복하려고합니다.json-simple, 파일에서 읽기

{ 
    "myDevicesInfo": 
    [ 
     { 
      "DeviceType":"foo", 
      "DeviceName":"foo1", 
      "IPAddress":"192.168.1.1", 
      "UserName":"admin", 
      "Password":"pw" 
     } 
    ] 
} 
나는 내 키 - 값 쌍려고 다음과 같은 오류가 무엇입니까

: 스레드에서

예외를 "주"자바

파일은 다음 형식으로되어 있습니다 .lang.ClassCastException : org.json.simple.JSONArray를 org.json.simple.JSONObject에 캐스트 할 수 없습니다. at 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이므로 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 라이브러리에 없습니다. –