将 pojo class 中的变量名称更改为 kotlin 中的用户输入值

Changing the name of a variable in pojo class into a user input value in kotlin

我用谷歌搜索了几天,似乎找不到答案。

如何更改 pojo class 的变量名称以显示用户输入?

代码如下:

private fun writeJSONtoFile(s: String) {

    //This is the save function in the result data page
    val unit_result = findViewById<EditText>(R.id.unit_result)
    val mReading = findViewById<EditText>(R.id.mReading_result)

    val unit_res: String = unit_result.text.toString()
    val reading_Res: String = mReading.text.toString()

    //Create a Object of Gson
    var gson = Gson()


    val unit=Unit(reading_Res,"20:55")
    //And so on,
    val building=Building(listOf(unit))
    //Until the outer part of the structure
    val solstice=Solstice(building)


    //for (i in 1..2) {
    //}

    //Convert the Json object to JsonString
    var jsonString:String = gson.toJson(solstice)


    //Initialize the File Writer and write into file
    val file = File(s)


    try {

        FileOutputStream(file, false).bufferedWriter().use { writer -> writer.write((jsonString)) }
        //fileOutputStream.write(data.toByteArray())


    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    } catch (e: NumberFormatException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    } catch (e: Exception) {
        e.printStackTrace()
    }




}

这里是 classes:

package com.example.watermeterapp

data class Solstice(
    var building:Building
)

data class Building(
    var id: List<Unit>
)

data class Unit(
    var reading: String,
    var timeStamp: String
)

预期结果:

{"Building":{"A-01-013":[{"Reading":"123123.42"}]}}

实际结果:

{"Building":{"id":[{"Reading":"123123.42"}]}}

有什么方法可以将 "id" 更改为任何用户输入吗?在 kotlin 中可以吗?想知道,任何帮助将不胜感激。

无法动态更改字段名称。但是,您可以使用 JSONObject 来构造您的对象。例如:

val unit = JSONObject()
unit.put("Reading", reading_Res)
val building = JSONObject()
building.put(userInput, listOf(unit))

这将产生:(假设 userInput = "A-01-013"

{"A-01-013":[{"Reading":"123123.42"}]}

然后,为了将其与您的预期结果相匹配,您只需将其包装在另一个 JSONObject:

val wrapper = JSONObject()
wrapper.put("Building", building)

这导致:

{"Building":{"A-01-013":[{"Reading":"123123.42"}]}}

要获取此 JSON 对象的字符串表示形式,您可以简单地使用 toString() 方法:

writer.write(wrapper.toString())