如何在Android的Kotlin中把数据输出为JSON数组?

0 人关注

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数组?

3 个评论
你需要创建一个Cars列表,并将其序列化为JSON,你的 CarList 类应该被命名为 Car ,你的 carList 对象应该被创建为 Car 的列表。 例子。【替换代码4
@mhdwajeeh.95 谢谢你的建议!我已经通过这个得到了基本的功能工作:)
android
json
kotlin
Noren
Noren
发布于 2021-01-06
1 个回答
Noren
Noren
发布于 2021-01-07
已采纳
0 人赞同

要想正确格式化这一点,请将

var carlist: CarList = CarList(brand, model, year, color, type, price)
var carlist = listOf(CarList(brand, model, year, color, type, price))

这将以下列格式保存数据。carlist.json

"brand": "Toyota", "color": "Red", "model": "Prius", "price": 6.0, "type": "Hatchback", "year": 2009

要增加更多的条目,可以这样格式化数据。

var carlist = listOf(