【问题标题】:How do I output data as a JSON Array in Kotlin on Android?如何在 Android 上的 Kotlin 中将数据输出为 JSON 数组?
【发布时间】: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 谢谢你!我已经掌握了这个函数的基础知识:)

标签: android json kotlin


【解决方案1】:

要正确格式化,请替换

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(
  CarList(brand1, model1, year1, color1, type1, price1),
  CarList(brand2, model2, year2, color2, type2, price2)
)

这将以 JSON 数组的正确格式保存。

【讨论】:

    猜你喜欢
    • 2012-03-21
    • 2021-06-18
    • 1970-01-01
    • 2020-04-29
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多