我的 Kotlin API 类 如何从 json 构建? (使用摩西)
How can my Kotlin API classes be constructed from json? (using Moshi)
我正在重构并添加到应用程序的 API 通信中。我想了解我的 "json data objects" 的用法。直接使用属性或从 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"...因为...我想摆脱,但我不知道如何摆脱。上面的 class 有效(给予或采取是否允许返回或不返回可选对象等等)但它只是让我感到困扰,因为我在尝试进行这个漂亮干净的重载初始化时遇到了困难。
它也不一定是数据 class,但它在这里似乎很合适。
你无法以任何高效的方式真正做到这一点。任何构造函数调用都会实例化一个新对象,但由于 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)
}
}
我正在重构并添加到应用程序的 API 通信中。我想了解我的 "json data objects" 的用法。直接使用属性或从 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"...因为...我想摆脱,但我不知道如何摆脱。上面的 class 有效(给予或采取是否允许返回或不返回可选对象等等)但它只是让我感到困扰,因为我在尝试进行这个漂亮干净的重载初始化时遇到了困难。
它也不一定是数据 class,但它在这里似乎很合适。
你无法以任何高效的方式真正做到这一点。任何构造函数调用都会实例化一个新对象,但由于 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)
}
}