google / google/gson

Gson cannot serialize subclass who override a field

Open
#2,638 1 comment 1 reaction 0 assignees View on GitHub
bug kotlin
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

_I saw some others threads about it but I did not find a solution in them._

# Gson version
2.10.1

# Java / Android version
17

# Description
### The real context
I have a sealed class (heritance from Throwable) who represent all errors in my app (~80 inner dataclass). Sometime I want to override "message" or "reason" in my "sub dataclass", but when i try to serialize it with, an error occurs.

### A simple way to reproduce
```
open class MyClass {
open val a = 22
}
open class SubClass : MyClass() {
override val a = 25
val b = 12
}
```

## Expected behavior

- When I serialize MyClass, i expect to have { "a" : 22 }
- When I serialize SubClass, i expect to have { "a": 25, "b" : 12 }

## Actual behavior
It cannot serialize SubClass, "JSON fields named 'a'; conflict is caused by fields ...".
Also i tried handmade reflection on "SubClass" and i see "a" only one time. I guess you are using more complex mecanics.

#### Notes:
- I can't change the class Throwable (or use annotation in them)
- A can't make an adapter for all the 80 inner data class
- **I tried with Jackson json serialization and it works as expected**
```
val mapper = ObjectMapper()
val json = mapper.writeValueAsString(SubClass())
println(json)
```
Output : `{"a":25,"b":12}`

# Reproduction steps
Just run an unit test with the code below and call the methode Builder().toJson(SubClass())

# Exception stack trace
```
Class com.organisation.app.MyUnitTest$SubClass declares multiple JSON fields named 'a'; conflict is caused by fields com.organisation.app.MyUnitTest$SubClass#a and com.organisation.app.MyUnitTest$MyClass#a
java.lang.IllegalArgumentException: Class com.organisation.app.MyUnitTest$SubClass declares multiple JSON fields named 'a'; conflict is caused by fields com.organisation.app.MyUnitTest$SubClass#a and com.organisation.app.MyUnitTest$MyClass#a
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:302)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:130)
at com.google.gson.Gson.getAdapter(Gson.java:556)
at com.google.gson.Gson.toJson(Gson.java:834)
at com.google.gson.Gson.toJson(Gson.java:812)
at com.google.gson.Gson.toJson(Gson.java:759)
```

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.