Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

kotlin - How to serialize a class implementing a interface with gson?

There is a interface A:

interface A {
    val name: String
}

Also there is one class B implementing this interface:

class B() : A {
    val implementedName: String = "Test"

    override val name: String
        get() = implementedName
}

Then i try to serialize this class B:

val b: A = B()
Gson().toJson(b)

And geht the following output:

// Output
{"implementedName":"Test"}

I realize the gson to type erasure can't infere the type of the variable b, but what I want to see is gson serializing the interface fields:

// Output
{"name":"Test"}

How can i achieve this?

question from:https://stackoverflow.com/questions/65948068/how-to-serialize-a-class-implementing-a-interface-with-gson

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Gson can't do that. Using SerializedName annotation Android Studio highlights that it is not possible to do this. This annotation is not applicable to target 'member property without backing field or delegate. But implementing it this way should work.

interface A {
    val name: String
}

class B() : A {
    @SerializedName("your_name")
    override val name: String = "Test"
}

Then using Gson().toJson(b) the output should be:

{"your_name": "Test"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...