Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support gson RuntimeTypeAdapterFactory generation #30

Open
GediminasZukas opened this issue Oct 19, 2020 · 2 comments
Open

Support gson RuntimeTypeAdapterFactory generation #30

GediminasZukas opened this issue Oct 19, 2020 · 2 comments

Comments

@GediminasZukas
Copy link

gson-extras has such class: https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java which is helpful for polymorphic types serialization without reflection.

For example, it can be used to handle Kotlin sealed class serialization:

sealed class Shape {
        class Rectangle() : Shape()
        class Circle() : Shape()
}
val adapter: RuntimeTypeAdapterFactory<Shape> = RuntimeTypeAdapterFactory.of(Shape::class.java)
        .registerSubtype(Rectangle::class.java)
        .registerSubtype(Circle::class.java)

And then in your gson instance builder:

registerTypeAdapterFactory(adapter)

However, seems it is a boilerplate and not safe solution to write such factory for every sealed class in the project. Would be nice to handle it with annotations like kotlinx-serialization does with polymorphic serialization problems: https://medium.com/@andreclassen1337/goodbye-runtimetypeadapterfactory-polymorphic-serialization-using-kotlinx-serialization-46a8cec36fdc

@Polymorphic
sealed class Shape {
        @SerialName("Rectangle")
        class Rectangle() : Shape()
        @SerialName("Circle")
        class Circle() : Shape()
}
@aafanasev
Copy link
Owner

@GediminasZukas that's a great idea! I'll have a look and keep you updated

@GediminasZukas
Copy link
Author

I've made a tiny library which tries to solve this problem: https://github.com/GediminasZukas/PolyAssistant Feel free to use any idea from it if you find it helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants