Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 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 Answer

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"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...