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

Hett :

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?

Hett :

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);
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421706&siteId=1