J Freebird
J Freebird

Reputation: 3910

Gson: Deserialize Json into Abstract Class

I have json that contains:

{"timeZone": "America/Los_Angeles"}

among many other keys, and I want to deserialize it into java.util.TimeZone. TimeZone is just a field in a class that I want to instantiate with this json.

The issue is that TimeZone is an abstract class and it should be instantiated with:

public static synchronized TimeZone getTimeZone(String ID) {
        return getTimeZone(ID, true);

which uses a concrete class ZoneInfo to instantiate. The deserializer, however, calls the constructor of TimeZone by default. So I got:

java.lang.RuntimeException: Failed to invoke public java.util.TimeZone() with no args

I wonder how to configure Gson to instantiate a TimeZone from the above json?

Upvotes: 3

Views: 2843

Answers (1)

Ben
Ben

Reputation: 6059

You'd need to create something like a Gson TypeAdapter and register it with your Gson instance.

I'm not sure how/whether this will work for your particular data format, but here's an example that I've used in my own projects:

public class TimeZoneAdapter extends TypeAdapter<TimeZone> {
  @Override
  public void write(JsonWriter out, TimeZone value) throws IOException {
    out.value(value.getID());
  }

  @Override
  public TimeZone read(JsonReader in) throws IOException {
    return TimeZone.getTimeZone(in.nextString());
  }
}

You would then register it when building a Gson instance like so:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(TimeZone.class, new TimeZoneAdapter());

Gson gson = builder.create();

Hope this helps!

Upvotes: 5

Related Questions