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
)
}
This outputs the following, as the user inputs:
{
"brand": "Toyota",
"color": "Red",
"model": "Prius",
"price": 6.0,
"type": "Hatchback",
"year": 2009
}
However, I am trying to get the data to save as a JSON array, like so:
[
{
"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 (a class)
class CarList(val brand: String, val model: String, val year: Int, val color: String, val type: String, val price: Double) {
}
How do I change my code to output as the format I desire, a JSON array?