Multiple GSON @SerializedName per field?

Gus picture Gus · Sep 7, 2014 · Viewed 40.3k times · Source

Is there any way in Gson to map multiple JSON fields to a single Java object member variable?

Let's say I have a Java class...

public class MyClass {
    String id;
    String name;
}

I want to use this single class with two different services. However, these two services differ in how they return their data...

{ "id": 2341, "person": "Bob" }

... and ...

{ "id": 5382, "user": "Mary" }

... respectively.

Is there any way to map both the "person" and "user" fields in the JSON string to the name field in the Java object?

(Note: I only ever need to convert from JSON string to Java object - never the other way around.)

Answer

Mathieu Castets picture Mathieu Castets · Mar 17, 2016

In October 2015, Gson version 2.4 (changelog) added the ability to use alternate/multiple names for @SerializedName when deserializing. No more custom TypeAdapter needed!

Usage:

@SerializedName(value="name", alternate={"person", "user"})

https://www.javadoc.io/doc/com.google.code.gson/gson/2.6.2/com/google/gson/annotations/SerializedName.html