GSON 2.0+ deserializes a field from two different serialized field names

In my Java class, I have a field declared as follows:

protected double a = 0.0;

In JSON, which is deserialized to recreate this class, this field can be displayed with either of two different names (obsolete problem). For example, a JSON field might look like this:

"a": 9.57,

or like this:

"d": 9.57,

(Fortunately, the deprecated name "d" does not cause names to collide with any other variables.)

My problem is that I need to fill in the class "a" field with either the JSON key "a" or "d" - depending on what is present. (I believe that they are always mutually exclusive, but in fact I have not proved this, without a doubt.)

I am using Gson 2.2.1 and Java 7 in Netbeans.

+4
2

JsonDeserializer, JSON POJO, .

. GSON

:

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());
+1

2015 Gson 2.4 (changelog) ​​ / @SerializedName . TypeAdapter!

:

@SerializedName(value="default_name", alternate={"name", "firstName", "userName"})
public String name;

:

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

https://google.imtqy.com/gson/apidocs/com/google/gson/annotations/SerializedName.html

+2

Source: https://habr.com/ru/post/1544666/


All Articles