Right now, my code looks like this AddActivity.kt
fun addCarToJSON(brand: String, model: String, year: Int, color: String, type: String, price: Double) {
// TODO: finish function to append data to JSON file
var carlist: CarList = CarList(brand, model, year, color, type, price)
val gsonPretty = GsonBuilder().setPrettyPrinting().create()
val newCarInfo: String = gsonPretty.toJson(carlist)
saveJSON(newCarInfo)
fun saveJSON(jsonString: String) {
val output: Writer
val file = createFile()
output = BufferedWriter(FileWriter(file))
output.write(jsonString)
output.close()
private fun createFile(): File {
val fileName = "carlist.json"
val storageDir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
if (storageDir != null) {
if (!storageDir.exists()){
storageDir.mkdir()
return File(
storageDir,
fileName
这将输出以下内容,作为用户的输入。
"brand": "Toyota",
"color": "Red",
"model": "Prius",
"price": 6.0,
"type": "Hatchback",
"year": 2009
然而,我试图让数据保存为一个JSON数组,像这样。
"brand": "Toyota",
"model": "RAV4",
"year": 2016,
"color": "red",
"type": "SUV",
"price": 27798.0
"brand": "Mitsubishi",
"model": "Lancer",
"year": 2010,
"color": "grey",
"type": "sedan",
"price": 10999.0
For reference, here is CarList.kt(一个班级)
class CarList(val brand: String, val model: String, val year: Int, val color: String, val type: String, val price: Double) {
我如何改变我的代码以输出我想要的格式,一个JSON数组?