google / gson

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

class declares multiple JSON fields - How to tell Gson to consider child class field. #1420

Open Padmahas opened 5 years ago

Padmahas commented 5 years ago

Hello,

We are using Google Ad Manager axis API in our project. While converting LineItem object, we are getting the below error.

java.lang.IllegalArgumentException: class com.google.api.ads.admanager.axis.v201808.CustomCriteriaSet declares multiple JSON fields named __equalsCalc
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:170) ~[gson-2.8.0.jar:?]
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100) ~[gson-2.8.0.jar:?]
    at com.google.gson.Gson.getAdapter(Gson.java:423) ~[gson-2.8.0.jar:?]
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115) ~[gson-2.8.0.jar:?]

As mentioned in this issue, using exclusion strategy will make those fields to be null. Since those fields are mandatory, if it's sent to Ad manager we will get exception.

Hence I'm look for a way to tell Gson, instead of completely excluding the field from Deserialization, how to force Gson to consider child class fields and child class setter methods?

When it's common for a field to override it's parent class field, why not Gson consider child class's field by default? How can I overcome this exception?

Thank you.

Padmahas commented 5 years ago

Update. Hello,

I'm still getting the multiple fields error irrespective of whether I check, it's declared in parent or not. Either if I exclude a field only if it is declared in parent class, as described in this SO answer, OR I blindly exclude all "equalsCalc" and "hashCodeCalc", there's no difference.

Either way, somehow I need to tell Gson to consider child class field. How to achieve that.

Thank you.

cedric05 commented 5 years ago

any update??

Padmahas commented 5 years ago

Yeah. I excluded all "equalsCalc" and "hashCodeCalc", irrespective of whether it is parent or child class. Then I had to provide custom Deserialization for all classes which throws this error.

Thank you.

harezmi1907 commented 1 year ago

I was on a project to retire all the other JSON libraries and use GSON instead. I kept getting this error and had to leave some as they were. I don't want to use the exclusion strategy, either because there are many fields need to be excluded.