gpt4 book ai didi

kotlin - 如何从json构造我的Kotlin API类? (使用莫西)

转载 作者:行者123 更新时间:2023-12-02 13:23:16 25 4
gpt4 key购买 nike

我正在重构并添加到应用程序的API通信中。我想将这种用法用于“json数据对象”。直接使用属性或从json字符串实例化。

userFromParams = User("user@example.com", "otherproperty")
userFromString = User.fromJson(someJsonString)!!
// userIWantFromString = User(someJsonString)

让userFromParams序列化为JSON并不是问题。只需添加toJson()函数即可解决此问题。
data class User(email: String, other_property: String) {
fun toJson(): String {
return Moshi.Builder().build()
.adapter(User::class.java)
.toJson(this)
}

companion object {
fun fromJson(json: String): User? {
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
return moshi.adapter(User::class.java).fromJson(json)
}
}
}

我要摆脱的是“fromJson”,因为……我想,但我不知道怎么做。上面的类可以工作(允许或不允许返回一个可选对象等等),但它使我感到困惑,因为我无法进入干净整洁的重载初始化。

它也不一定非要是数据类,但在这里看起来确实合适。

最佳答案

您实际上无法以任何高效的方式做到这一点。任何构造函数调用都将实例化一个新对象,但是由于Moshi在内部处理对象创建,因此您将拥有两个实例...

如果您真的很想要它,可以尝试以下方法:

class User {
val email: String
val other_property: String

constructor(email: String, other_property: String) {
this.email = email
this.other_property = other_property
}

constructor(json: String) {
val delegate = Moshi.Builder().build().adapter(User::class.java).fromJson(json)
this.email = delegate.email
this.other_property = delegate.other_property
}

fun toJson(): String {
return Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
.adapter(User::class.java)
.toJson(this)
}
}

关于kotlin - 如何从json构造我的Kotlin API类? (使用莫西),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235691/

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