1

我正在重构并添加到应用程序的 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”......因为......我想要但我不知道如何。上面的类有效(给予或接受是否允许返回可选对象等等)但它只是让我感到困扰,因为我在试图进行这个漂亮干净的重载初始化时遇到了困难。

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

4

1 回答 1

2

你不能以任何高效的方式真正做到这一点。任何构造函数调用都会实例化一个新对象,但由于 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)
    }
}
于 2018-05-08T14:43:50.043 回答