gson 如何将对象的Kotlin数组转换为json数组并保留访问键名?

ogsagwnx  于 2022-11-06  发布在  Kotlin
关注(0)|答案(2)|浏览(405)

我有一个API,它要求json请求以特定的数组形式,其中数组对象字段是用名称访问的,然后使用Retrofit发布。请参考下面的代码:
Kotlin:

class RailPoint(
 var railPointId,
 var startTime,
 var endTime
)

var rails: ArrayList<RailPoint>()
rails.add(RailPointObject1)
rails.add(RailPointObject2)

因此,将上面的rails数组转换为json后,应该会产生以下结果:

{
  "railPoint[0][railPointId]": 5,
  "railPoint[0][startTime]": "",
  "railPoint[0][endTime]": "2021-10-19 07:37:19",
  "railPoint[1][railPointId]": 1,
  "railPoint[1][startTime]": "2021-10-19 07:33:37",
  "railPoint[1][endTime]": "2021-10-19 07:35:20",
}

那么,怎样才能实现这种类型的json数组形式呢?

46qrfjad

46qrfjad1#

首先让Gson将列表序列化为一个JsonArray,然后将元素组合为一个新的JsonObject,再将该对象序列化为JSON,可以解决这个问题:

val rails: List<RailPoint> = ...

val gson = Gson()
val railsJsonList = gson.toJsonTree(rails).asJsonArray!!
val railsJsonObject = JsonObject()
// Transform elements
for (i in 0 until railsJsonList.size()) {
    val railPointJson = railsJsonList[i].asJsonObject

    for ((name, value) in railPointJson.entrySet()) {
        railsJsonObject.add("railPoint[$i][$name]", value)
    }
}
println(gson.toJson(railsJsonObject))

相关问题