google / gson

A Java serialization/deserialization library to convert Java Objects into JSON and back
Apache License 2.0
23.23k stars 4.27k forks source link

About gson multiple field conflict error reporting #2589

Closed LyingDoc closed 3 months ago

LyingDoc commented 8 months ago

Gson version

2.10.1

Java / Android version

1.8

Description

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'init' defined in class path resource [com/sm/sms/config/InitAliPay.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.ijpay.alipay.AliPayApiConfig]: Factory method 'init' threw exception; nested exception is java.lang.IllegalArgumentException: Class com.alipay.api.DefaultAlipayClient declares multiple JSON fields named 'signChecker'; conflict is caused by fields com.alipay.api.DefaultAlipayClient#signChecker and com.alipay.api.AbstractAlipayClient#signChecker

Expected behavior

When I use gson to convert to json, the problem described above occurs, that is, the conversion indicates field conflicts and the conflicting fields are not automatically excluded. Currently, json.paser can be used to solve this bug. This bug can be optimized and used in the future to verify the problem.

Marcono1234 commented 8 months ago

You can probably work around this by using an ExclusionStrategy which excludes one of the fields, or a FieldNamingStrategy which renames one of the fields.

However, the actual problem here seems to be that you are trying to serialize a class (DefaultAlipayClient) which was most likely never intended to be serialized to or from JSON. And because Gson has no built-in adapter for this class, it relies on reflection to access the internal fields of that class. If possible the best solution would be to not serialize DefaultAlipayClient to JSON in the first place.

conflicting fields are not automatically excluded [...] This bug can be optimized and used in the future to verify the problem

Can you please describe a bit more in detail what behavior you expected here? Excluding conflicting fields automatically seems quite error-prone because the JSON data would then be incomplete, and on deserialization fields would remain uninitialized.

Conflicting fields have to be handled manually by the developer, in the way that is most appropriate for the specific use case.

Marcono1234 commented 3 months ago

I am going to close this because no answer has been provided. The comment above explains how to handle conflicting field names, and why Gson does not automatically exclude one of them.