Kotlin – 使用扩展类中的函数编码属性的 JSON。

huangapple go评论57阅读模式
英文:

Kotlin - encode json of properties using function from extended class

问题

我尝试使用扩展类中的函数进行 Json.encodeToString:

子类

class Body(
            var variable1: String,
            var variable2: String,
            var variable3: Int,
        ): Serializable()

父类

@Serializable
open class Serializable {

    fun getJson(): String{
        return Json.encodeToString(this)
    }
}

使用

var body = Body("1","1",1)
var json = body.getJson()

这将得到 "{}"。我认为它从父类中获取属性。

编辑:

我需要在 Serializable 类中使用注解,因为我需要将不同的对象放入一个函数中:

var body = Body("1","1",1)
var response = RequestServer.Request<Boolean>("route/set", body, HttpMethod.Put)

var body2 = Body2("2","2",2)
var response = RequestServer.Request<Boolean>("route/set", body2, HttpMethod.Put)

函数:

suspend inline fun <reified T> Request(route: String, body: Serializable, method: HttpMethod): BaseResponse<T> {
            var response: HttpResponse = client.request(Address + route) {
                        this.method = method
                        contentType(ContentType.Application.Json)
                        setBody(Json.encodeToString(body))
                    }

            return Json{ ignoreUnknownKeys = true }.decodeFromString(response.bodyAsText())
        }

如何使它从子类中获取属性?

英文:

I try to Json.encodeToString using function from extended class:

Child class

class Body(
            var variable1: String,
            var variable2: String,
            var variable3: Int,
        ): Serializable()

Parent class

@Serializable
open class Serializable {

    fun getJson(): String{
        return Json.encodeToString(this)
    }
}

Using

var body = Body(&quot;1&quot;,&quot;1&quot;,1)
var json = body.getJson()

And this get "{}". I think it takes properties from the parent class.

EDIT:

I need annotation in Serializable class because i need to put different objects to one function:

var body = Body(&quot;1&quot;,&quot;1&quot;,1)
var response = RequestServer.Request&lt;Boolean&gt;(&quot;route/set&quot;, body, HttpMethod.Put)

var body2 = Body2(&quot;2&quot;,&quot;2&quot;,2)
var response = RequestServer.Request&lt;Boolean&gt;(&quot;route/set&quot;, body2, HttpMethod.Put)

Function:

suspend inline fun &lt;reified T&gt; Request(route: String, body: Serializable, method: HttpMethod): BaseResponse&lt;T&gt; {
        var response: HttpResponse = client.request(Address + route) {
                    this.method = method
                    contentType(ContentType.Application.Json)
                    setBody(Json.encodeToString(body))
                }

        return Json{ ignoreUnknownKeys = true }.decodeFromString(response.bodyAsText())
    }

How to make it take properties from child class?

答案1

得分: 1

这是因为在父类中使用了 @Serializable 注解,并且 getJson() 方法尝试对其自身进行序列化。

所以你可以将注解放在子类而不是父类中。

另外,为了最佳实践,你可以更改父类名称,以避免与标准 Kotlin 接口混淆。

编辑

我现在明白了,你是想构建一些 API,对吗?那么我在使用 Kotlin + Spring 时实际上做的是使用数据类。数据类可以通过魔法来进行 JSON 的序列化和反序列化。

查看 Baeldung 上的这篇文章,它基本上可以满足你的需求,还使用了扩展函数:
https://www.baeldung.com/kotlin/data-class-json-serialize-default-values

关于数据类的 Kotlin 文档:
https://kotlinlang.org/docs/data-classes.html

英文:

That's because the use of @Serializable in the parent class and the method getJson() tries to serialize itself.

So, what you can do is to put the annotation in the child class, instead of the parent class.

Also, for best practices, you can change your parent class name, to avoid confusion with the standard Kotlin interface.

EDIT

I get it now you are trying to build some API, right? So what I do actually when using Kotlin + Spring is to use a data class. The data class does the magic to serializing and deserializing JSON.

Check this article in Baeldung, it basically does what you need and also uses the extension function:
https://www.baeldung.com/kotlin/data-class-json-serialize-default-values

Kotlin docs about data classes:
https://kotlinlang.org/docs/data-classes.html

huangapple
  • 本文由 发表于 2023年5月17日 19:44:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定