【发布时间】:2021-01-06 07:14:33
【问题描述】:
现在,我的代码看起来像这样 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
}
]
供参考,这里是CarList.kt(一个类)
class CarList(val brand: String, val model: String, val year: Int, val color: String, val type: String, val price: Double) {
}
如何将代码更改为我想要的格式输出,即 JSON 数组?
【问题讨论】:
-
您需要创建一个 Cars 列表,并将其序列化为 JSON,您的
CarList类应命名为Car。并且您的carList对象应创建为Car的列表。前任。var carlist= listOf( Car(brand1, model1, year1, color1, type1, price1), Car(brand2, model2, year2, color2, type2, price2) ) -
@mhdwajeeh.95 谢谢你!我已经掌握了这个函数的基础知识:)