Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从json构建我的Kotlin API类?(使用Moshi)_Kotlin_Moshi - Fatal编程技术网

如何从json构建我的Kotlin API类?(使用Moshi)

如何从json构建我的Kotlin API类?(使用Moshi),kotlin,moshi,Kotlin,Moshi,我正在重构并添加到应用程序的API通信中。我想了解一下我的“json数据对象”的用法。直接使用属性或从json字符串实例化 userFromParams = User("user@example.com", "otherproperty") userFromString = User.fromJson(someJsonString)!! // userIWantFromString = User(someJsonString) 让userFromParams序列化为JSON不是问题。只需添加一

我正在重构并添加到应用程序的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)
    }
}

缓存Moshi实例和用户JsonAdapter以供重用。适配器的创建非常简单,并且可以快速重用。当然。这只是一个快速而肮脏的胡说八道的示例类。但是谢谢你澄清这不是一个好的做法。谢谢你的例子。这满足了我的好奇心。。。我甚至认为我可能会接受你的建议,不会产生过多的实例。