tpcordeiro
tpcordeiro

Reputation: 443

How to change @SerializedName, from GSON, of an attribute in a extended class

I have a class like this:

class A {
    @Expose
    @SerializedName("a_id")
    private String id;
}

Now I want to create class B that extends A, but, in B, I want to change the SerializedName of id to "b_id". Is there a way to do this?

Upvotes: 7

Views: 8028

Answers (3)

Alberto M
Alberto M

Reputation: 1760

this is what I did: I extended the class A, added a new parameter with the new serializer, and then the overridden getter returns the new parameter:

class B extends A {

    @SerializedName("b_id")
    private String newId;

    @Override
    public @NotNull String getId() {
        return newId;
    }
}

Upvotes: 0

Reinzekuken
Reinzekuken

Reputation: 9

apply @SerializedName("b_id") to the setter in B

class B { private String id;

@SerializedName("b_id")
private void setId(String id);

}

Upvotes: -1

Jesse Wilson
Jesse Wilson

Reputation: 40613

It isn't possible out of the box. You'll need to write a custom type adapter. See the Custom Serialization and Deserialization section of the Gson user's guide.

Upvotes: 2

Related Questions