以下是以json格式存储在json文件中的设备详细信息列表。
{"Device_details":[
{"DUT1":
{"Interface":"eth1",
"IP_address":"40.0.0.1/24"},
"DUT3":
{"Interface":"eth3",
"IP_address":"40.0.0.3/24"},
"DUT2":
{"Interface":"eth2",
"IP_address":"40.0.0.2/24"
}
}
]}
我想遍历每个设备并打印出与单个DUT对应的列表中每个设备的接口和IP地址。
示例输出:
Device : DUT1
Interface : eth1
IP_address : 40.0.0.1/24
Device : DUT2
Interface : eth2
IP_address : 40.0.0.2/24
等...... 显示的设备顺序无关紧要,我想使用GSON执行此操作。 到目前为止我的代码:
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader(fileName.json));
jsonObject = jsonElement.getAsJsonObject();
JsonArray devices = jsonObject.getAsJsonArray("Device_details");
JsonElement device_list = devices.get(0);
JsonObject devices_object= device_list.getAsJsonObject();
System.out.println(devices_object.size());
for (int i=0; i < devices_object.size(); i++){
//How do I access the devices and it's details
};
答案 0 :(得分:2)
public static void main(String[] args) throws FileNotFoundException {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader("pathToJson.json"));
Response res = gson.fromJson(reader, Response.class);
for (Map<String, Device> map : res.Device_details) {
for (Map.Entry<String,Device> e : map.entrySet()){
System.out.println("Device : " + e.getKey());
Device device = e.getValue();
System.out.println("Interface : " + device.Interface);
System.out.println("IP_address : " + device.IP_address);
}
}
}
class Device {
String Interface;
String IP_address;
}
class Response {
List<HashMap<String, Device>> Device_details = new ArrayList();
}
JsonReader
和gson.fromJson
允许您将json映射到java对象。
此处,Response
是&#34;根元素&#34;。其属性Device_details
必须与json中的名称相同。