google / google/gson

Problem with TypeAdapterRuntimeTypeWrapper and logic in MapTypeAdapterFactory

Open
#1,748 4 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

Here's my Kotlin model:
```kt
sealed class X {
object A : X()
object B : X()
object C : X()
}

data class Y(
val a: A,
val map: Map)

val y = Y(X.A, mapOf("a", X.A))
```
I would like to serialize `y`. I have set a type adapter for X, but also for A.

The problem arises in `MapTypeAdapterFactory`. It will wrap the adapters in `TypeAdapterRuntimeTypeWrapper`:

![Screen Shot 2020-08-05 at 2 42 50 PM](https://user-images.githubusercontent.com/2679255/89467174-fa3aa600-d729-11ea-940a-560da236e2ff.png)

`TypeAdapterRuntimeTypeWrapper` has a dubious logic to look for a "better" adapter based on runtime type:

![Screen Shot 2020-08-05 at 2 44 06 PM](https://user-images.githubusercontent.com/2679255/89467286-235b3680-d72a-11ea-9b44-621dcdd489c7.png)

This completely breaks my serialization, because now `X.A` inside a map will be serialized using type adapter for `A` instead of for `X`.

The logic inside `TypeAdapterRuntimeTypeWrapper` is very questionable. If we already have an adapter based on map's value type, why do we look at runtime type at all? Sure, runtime type will be more specific, and its adapter more specific, but using the said runtime adapter does not make sense in the context of generic value type, and will be impossible to deserialize. I don't see any case where this logic would make sense.

Is it possible to make this logic optional? Basically, I do **not** want to wrap map's value type in `TypeAdapterRuntimeTypeWrapper`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.