我尝试使用以下代码从JSON
文件中读取数据:
FileReader reader = new FileReader(file);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray dataName = (JSONArray)jsonObject.get("results");
Iterator it = dataName.iterator();
while (it.hasNext()) {
JSONObject out = (JSONObject) it.next();
System.out.printf("Game name: " + out.get("name") + " in plataforms:");
JSONArray data_plat = (JSONArray) out.get("platforms");
if (!data_plat.isEmpty()) {
Iterator it2 = data_plat.iterator();
while (it2.hasNext()) {
System.out.printf("I AM HERE");
JSONObject out_plat = (JSONObject) it2.next();
System.out.printf("\n- " + out_plat.get("name"));
}
}
}
这段代码在这篇文章中抛出NullPointerException
:
if (!dataPlat.isEmpty());
我已经分析了我的输出和JSON
文件,这是因为我读取的部分包含空值。我怎么能避免这个?
编辑:这是JSON
的一部分:
{
"name":"FIFA Manager 08",
"platforms":[
{
"api_detail_url":"http:\/\/www.giantbomb.com\/api\/platform\/3045-94\/",
"id":94,
"name":"PC",
"site_detail_url":"http:\/\/www.giantbomb.com\/pc\/3045-94\/",
"abbreviation":"PC"
}
],
"resource_type":"game"
},
{
"name":"FIFA Online 2",
"platforms":null,
"resource_type":"game"
},
错误发生在"platforms":null