简体   繁体   中英

How to use multiple JSON fields with the same name

I want to use two different type adapters for each field, this is using GSON 2.7.

I am getting the error “class declares multiple JSON fields named type”

public abstract class Vehicle 
{
    @SerializedName("type")
    @JsonAdapter(VehicleTypeAdapter.class)
    protected String type;
}
public class Car extends Vehicle
{ 
    @SerializedName("type")
    @JsonAdapter(CarTypeAdapter.class)
    protected CarType carType;
}

How to avoid this error? I tried using transient but it did not work.

As the error suggests, you can't have duplicate instances of a name used to serialize a field.

However, it doesn't look like you're trying to define two separate fields, but instead you're trying to create a more specific implementation of type in your Car class.

Unfortunately, by using extends you are adding onto the Vehicle abstract class rather than implementing a specific instance of type , so you can't change the definition of the inherited field.

Therefore, it looks like you've got a couple options:

  • Drop CarType altogether, and just use String type as inherited from the superclass.

  • If CarType is important to your implementation, you can change String type to VehicleType vehicleType and have CarType inherit from VehicleType , still removing the duplicate field from the Car subclass.

This means that you'll only have 1 @JsonAdapter so this option only works if creating a generic TypeAdapter.class is a possible solution.

  • If you really must redefine the field, you'll have to turn Vehicle into an interface so that you can shadow/redefine within a more specific scope. Not sure if this is viable for your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM