【问题标题】:How can my Kotlin API classes be constructed from json? (using Moshi)如何从 json 构造我的 Kotlin API 类? (使用 Moshi)
【发布时间】:2018-05-08 14:09:49
【问题描述】:

我正在重构并添加应用程序的 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 实例和您的用户 JsonAdapter 以供重用。适配器的创建和重用速度都非常重要。
  • 当然。这只是一个快速而肮脏的废话示例课程。但感谢您澄清这不是好习惯。

标签: kotlin moshi


【解决方案1】:

您无法以任何高效的方式真正做到这一点。任何构造函数调用都会实例化一个新对象,但由于 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)
    }
}

【讨论】:

  • 感谢您的示例。这满足了我的好奇心......甚至认为我可能会接受你的建议并且不会产生过多的实例。
猜你喜欢
  • 2020-10-18
  • 1970-01-01
  • 2019-12-03
  • 2019-11-20
  • 1970-01-01
  • 2020-09-03
  • 2019-11-12
  • 2019-05-05
  • 2021-03-21
相关资源
最近更新 更多