我正在嘗試閱讀包含不同自行車數組的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