[英]json-simple, reading from a file
我試圖遍歷文件系統中的一個文件,該文件包含許多設備的配置信息。
該文件的格式如下:
{
"myDevicesInfo":
[
{
"DeviceType":"foo",
"DeviceName":"foo1",
"IPAddress":"192.168.1.1",
"UserName":"admin",
"Password":"pw"
}
]
}
嘗試獲取內部鍵值對時出現以下錯誤:
線程“主”中的異常java.lang.ClassCastException:org.json.simple.JSONArray無法在mav2bac.main(bac.java:98)的mav2bac.loadDevices(bac.java:98)處轉換為org.json.simple.JSONObject。 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進行轉換並實例化包含這些值的對象的正確方法是什么?
問題是myDevicesInfo
是json對象的數組,而不是json對象。 所以下面這行:
JSONObject deviceAttributes = (JSONObject) jsonObject.get("myDevicesInfo");
需要更改為
JSONArray deviceAttributes = (JSONArray) jsonObject.get("myDevicesInfo");
嘗試這個 :
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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.