Hett
Hett

Reputation: 3824

How to convert json timezone object to java TimeZone using Gson?

The server provides next response:

"timezone": {
    "gmtOffset": 7,
    "timeZoneId": "Asia/Novosibirsk",
    "dstOffset": 7
}

I use Gson to parse this json. I tried to add field private TimeZone timezone to my DTO but Gson does not understand and throws the error:

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

Is there an easy way to solve this?

Upvotes: 1

Views: 226

Answers (1)

Hett
Hett

Reputation: 3824

It is someone`s custom fields set. Only custom deserializer may help.

public class TimeZoneDeserializer implements JsonDeserializer<TimeZone> {

    @Override
    public TimeZone deserialize(
            JsonElement jsonElement,
            Type type,
            JsonDeserializationContext jsonDeserializationContext
    ) throws JsonParseException {
        String timezoneId = jsonElement
                .getAsJsonObject()
                .get("timeZoneId")
                .getAsString();

        return TimeZone.getTimeZone(timezoneId);
    }
}

Upvotes: 2

Related Questions