Gson, Deserialize Wrapper class

I need help with the gson library, basically i have to de-serialize a wrapper class defined like this:

static class WrapperClass {
    public int value;
    private final String otherData;

    public WrapperClass(String otherData) {
        this.otherData = otherData;
    }

}

The class that I have to “jsonize” has fields like this:

private final WrapperClass wrappedData = new WrapperClass("other data");

The serializer of the wrapper class is really simple:

@Override
public JsonElement serialize(WrapperClass src, Type typeOfSrc, JsonSerializationContext context) {
    return context.serialize(src.value);
}

The problem is the de-serialization side, I should not re-instantiate the WrapperClass object because it’s already there by default, i have only to de-serialize it’s value, it’s possible to this with the gson library?

So, what you want to do: “read” the content of some JSON string and “overlay” existing objects with that.

I am not aware of a built-in way to do that. Beyond that: doing something of this complexity under the covers sounds like the wrong approach, too.

Thus, my recommendation: clearly separate those responsibilities. Meaning: instead of of creating a (almost counter-intuitive) solution that merges JSON data “into” existing objects: do that explicitly, it step by step. Like:

  • read the JSON data and de-serialize into one or more objects
  • then have an another special component “update” your “old” objects with the information found in the de-serialized objects