如何使用 Gson 将 json 时区对象转换为 java 时区?



服务器提供下一个响应:

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

我使用Gson来解析此json。 我试图将字段private TimeZone timezone添加到我的 DTO 中,但Gson不理解并抛出错误:

java.lang.RuntimeException: 未能调用没有参数的公共 java.util.TimeZone((

有没有简单的方法可以解决这个问题?

这是某人的自定义字段集。只有自定义反序列化程序可能会有所帮助。

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

最新更新