0
我不得不在Java中爲一個學校項目編寫一個小遊戲。 遊戲是RushHour,你可以在這裏看到一個例子:http://www.thinkfun.com/play-online/rush-hour/。如何在Java中使用JSON文件的輸出來創建對象?
我的老師現在問我允許我的代碼讀取一個外部文件,以便遊戲的初始狀態不再被硬編碼在我的主體中,並且遊戲的參數可以自定義(大小板,在遊戲中的汽車數量...)
這是我的第一個JSON文件,它設置了一個經典的遊戲。
{
"ClassicBoard" :
{
"height" : "6",
"width" : "6",
"exit":
{
"row" : "2",
"column" : "5"
}
},
"ListOfCars" :
{
"car2" :
{
"char" : "2",
"size" : "3",
"orientation" : "vertical",
"currentPosition":
{
"row" : "2",
"column": "2"
}
},
"car3" :
{
"char" : "3",
"size" : "3",
"orientation" : "vertical",
"currentPosition":
{
"row" : "2",
"column": "4"
}
}
},
"redCar":
{
"char" : "1",
"size" : "2",
"orientation" : "horizontal",
"currentPosition":
{
"row" : "2",
"column": "0"
}
}
}
我試圖找出如何讀取該文件,並重新使用它創建RushHourGame對象輸出。這是構造函數。
public RushHourGame(Board board, List <Car> cars, Car redCar) throws RushHourException
{
this.board = board;
this.redCar = redCar;
if(((redCar.getOrientation() == Orientation.HORIZONTAL)
&& (board.getExit().getRow() != redCar.getCurrentPosition().getRow()))
|| (((redCar.getOrientation() == Orientation.VERTICAL)
&& (board.getExit().getColumn() != redCar.getCurrentPosition().getColumn()))))
{
throw new RushHourException("Car must be aligned with the exit, "
+ "a default game has been created");
}
board.put(redCar);
for (Car putCars : cars)
{
board.put(putCars);
}
}
我試着用這樣的BufferedReader。
public static String readFile(String filename)
{
String result ="";
try
{
BufferedReader br = new BufferedReader (new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
line = br.readLine();
}
result = sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
但我不是如何使用它來解析我的JSON文件。有人可以幫助我嗎?
感謝您的回答。你的回答看起來很有意思,我會盡快詳細檢查,如果有效,我會回來給你打電話! –
嗯,我認爲這段代碼不是很有用,因爲我已經爲Car,Board,Position ...做了我的課程,而你所做的不適合它。另外,我認爲使用setter不是解決方案,因爲我不希望用戶有可能更改這些值。 RushHourGame類的構造函數調用所有其他類的cnstructor,因此,我只需要RushHourGame的構造函數來檢索JSON文件中的數據和值,並使用它創建一個新的RushHourGame對象。 但謝謝傑克遜的解決方案。 –