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.
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());