5

In my Java class I have a field declared like this:

protected double a = 0.0;

In the JSON that is deserialized to reconstitute this class, that field can appear with either of two different names (legacy issue). As an example, the JSON field can look like this:

"a": 9.57,

or like this:

"d": 9.57,

(Luckily, the legacy name "d" does not cause a naming collision with any other variables.)

My problem is that I need to populate the class field "a" with either the JSON key "a" or "d" -- whichever is present. (I believe they are always mutually exclusive, but I have not actually proven that beyond all doubt.)

I'm using Gson 2.2.1 and Java 7 in Netbeans.

MountainX
  • 6,217
  • 8
  • 52
  • 83

2 Answers2

5

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="default_name", alternate={"name", "firstName", "userName"})
public String name;

Example:

@SerializedName(value="a", alternate={"d"})
public double a;

https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html

Mathieu Castets
  • 5,861
  • 3
  • 28
  • 37
1

You need JsonDeserializer where you can check the specific key in the JSON string and based on its presence simply set the value in your custom POJO class as shown below.

For more info have a look at GSON Deserialiser Example

Sample code:

class MyJSONObject {
    protected double a = 0.0;

    public double getA() {
        return a;
    }

    public void setA(double a) {
        this.a = a;
    }

}

class MyJSONObjectDeserializer implements JsonDeserializer<MyJSONObject> {

    @Override
    public MyJSONObject deserialize(final JsonElement json, final Type typeOfT,
            final JsonDeserializationContext context) throws JsonParseException {

        JsonObject jsonObject = json.getAsJsonObject();

        MyJSONObject object = new MyJSONObject();

        if (jsonObject.get("a") != null) {
            object.setA(jsonObject.get("a").getAsDouble());
        } else if (jsonObject.get("d") != null) {
            object.setA(jsonObject.get("d").getAsDouble());
        }

        return object;
    }
}

...

String json = "{\"a\":\"9.57\"}";
// String json = "{\"d\":\"9.57\"}";
MyJSONObject data = new GsonBuilder()
        .registerTypeAdapter(MyJSONObject.class, new MyJSONObjectDeserializer()).create()
        .fromJson(json, MyJSONObject.class);

System.out.println(data.getA());
Braj
  • 46,415
  • 5
  • 60
  • 76