我正在尝试阅读包含不同自行车数组的JSON文件。当试图将自行车打印到java控制台时,我不断收到零点异常。我打算让所有的自行车都成为对象,但现在只是看看如何打印出来。阅读具有多个属性的JSON文件
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/bikes.json"));
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject);
JSONArray bikeList = (JSONArray) jsonObject.get("BikeList");
Iterator<String> iterator = bikeList.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
JSON文件:
{
"Search": {
"BikeList": [
{
"weight": "14.8",
"colour": "Blue",
"price": 149.99,
"name": "Hybrid Pro"
},
{
"weight": "15.8",
"colour": "Red",
"price": 249.99,
"name": "Slant comp"
},
{
"weight": "17.9",
"colour": "Pink",
"price": 500.00,
"name": "Charm"
}
]
}
}
(JSONArray),其中jsonObject.get( “搜索” ).get(“BikeList”)?您需要首先访问'Search',然后从对象中获取'BikeList'。 – StanislavL
为什么不尝试使用Jackson Json库? – Hector