Skip to content

Encode Gson request bodies using the runtime class - #3535

Merged
velo merged 1 commit into
OpenFeign:masterfrom
tanvir-ux:fix/gson-encoder-runtime-type
Sep 4, 2026
Merged

velo merged 1 commit into
OpenFeign:masterfrom
tanvir-ux:fix/gson-encoder-runtime-type

Conversation

@tanvir-ux

Copy link
Copy Markdown
Contributor

Fixes #2485.

Problem
When a Feign method declares an abstract (or superclass) body type, GsonEncoder serializes only the fields on that declared type. Fields on the concrete subclass never appear in the JSON.

Root cause
GsonEncoder.encode called gson.toJson(object, bodyType). Gson treats the second argument as the schema, so a SimpleTextMessage passed as Message is written as {"toUser":"..."}.

Fix
If bodyType is a raw Class, serialize with object.getClass(). Parameterized types (TypeToken / generics) still use the declared type so type arguments are not erased. Jackson and the other encoders are unchanged.

Tests
GsonCodecTest.encodesSubclassFieldsWhenBodyTypeIsAbstract encodes a subclass as the abstract type and asserts the JSON includes the subclass fields. Existing TypeToken encoding tests still pass.

./mvnw test -pl gson -am (gson: 11 tests, 0 failures).

GsonEncoder passed the declared parameter type into gson.toJson, so
subclass fields on an abstract request body type were dropped.

When bodyType is a raw Class, encode with object.getClass().
Parameterized types keep the declared TypeToken so generic arguments
are not erased.

Fixes OpenFeign#2485

@velo velo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean, correctly-scoped fix. Verified locally: mvn -pl gson -am test passes (all 12 gson tests green), the CHANGELOG entry matches the current SNAPSHOT version, and the fix lives in the one file that owns the problem rather than leaking into the shared codec layer. typeToEncode() correctly preserves ParameterizedType/TypeToken handling so the existing generics path isn't regressed. Two purely cosmetic nits (a stray comment-ratio note and one inconsistent text-block indent in the test) aren't worth holding this up for.

@velo
velo merged commit 0310d91 into OpenFeign:master Sep 4, 2026
3 checks passed
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

Successfully merging this pull request may close these issues.

incomplete Object information when serialize object with Gson

2 participants