2012-02-12 50 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 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 2012-02-13 00:26:00

+0

JSONArray是Java List,因此您可以按照迭代List的相同方式对它进行迭代。 – 271828183 2012-02-13 02:30:30

+0

这是我得到的输出:myDevicesInfo = [{DeviceType = bac,DeviceName = bac,IPAddress = 192.168.1.1,UserName = admins,Password = pw}]。我想获取方括号中的值。 – bentaisan 2012-02-13 17:06:16

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库中 – 2016-10-08 20:57:11