gpt4 book ai didi

json - 如何将数据类转换为 map

转载 作者:行者123 更新时间:2023-12-02 16:30:09 26 4
gpt4 key购买 nike

我试着转换成数据类来映射。 (代码下面只是示例代码)

data class User (
val name : String = "",
val age : Int = 0,
val deviceGroup: MutableSet<DeviceGroup> = mutableSetOf()
)
data class DeviceGroup (
val name : String = "",
val deviceLink : MutableSet<DeviceLink> = mutableSetOf()
)
data class DeviceLink (
val id : Int = 0,
val device : Device
)
data class Device (
val devId : Int = 0,
val name : String = ""
)

fun main (request : HttpServletRequest) {
val currentUser = request.session.getAttribute("user") as User
val data = userRepository.findByName(currentUser.name)

// return currentUser
// result is {name="test", age=17, deviceGroup = [{name="group1"}, {name="group2"}]}

// I want deserialization data class to Map
val response = data.deviceGroup.toMap()

response.deivceGroup.forEach {
// And add new key, pair
it.add(Map<String, MutableSet<Device>>("devices", mutableSetOf()))

// Lastly, I want put in the value
deviceGroupRepository.findByName(it.name).deviceLink.forEach {
it.devices.add(this)
}
}

return response
}

如果只返回数据值,则结果为 "{name="test", age=17, deviceGroup = [{name="group1"}, {name="group2"}]}"

如何将数据类转换为Map对象并添加新的 key 对?

最佳答案

使用associate将集合变成 map

Kotlin 标准库提供了一个名为 associate 的函数它将获取一组对象并将它们转换为 map 。它接受一个参数,该参数是一个指定映射的键和值应该是什么的函数。

例如,在您的情况下,您可以这样调用它:

val response = data.deviceGroup.associate { it.name to it.deviceLink }

它将返回 Map<String, MutableSet<DeviceLink>>其中关键是 name设备组,值为 deviceLink设置。


添加新值的最简单方法是简单地在它们后面附加 +运营商。

val response = data.deviceGroup.associate { 
it.name to it.deviceLink
} + mapOf("device" to emptySet())

如果你需要更多的控制,你可以使用 .toMutableMap()因此可以使用 put 添加新条目.

val response = data.deviceGroup.associate { 
it.name to it.deviceLink
}.toMutableMap()
response.put("device", emptySet())

关于json - 如何将数据类转换为 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63657413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com