如何使用 Gson 将 json timezone 对象转换为 java TimeZone?
How to convert json timezone object to java TimeZone using Gson?
服务器提供下一个响应:
"timezone": {
"gmtOffset": 7,
"timeZoneId": "Asia/Novosibirsk",
"dstOffset": 7
}
我用Gson
来解析这个json
。
我试图将字段 private TimeZone timezone
添加到我的 DTO,但 Gson
不理解并抛出错误:
java.lang.RuntimeException: Failed to invoke public java.util.TimeZone() with no args
有解决这个问题的简单方法吗?
这是某人的自定义字段集。只有自定义解串器可能有帮助。
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);
}
}
服务器提供下一个响应:
"timezone": {
"gmtOffset": 7,
"timeZoneId": "Asia/Novosibirsk",
"dstOffset": 7
}
我用Gson
来解析这个json
。
我试图将字段 private TimeZone timezone
添加到我的 DTO,但 Gson
不理解并抛出错误:
java.lang.RuntimeException: Failed to invoke public java.util.TimeZone() with no args
有解决这个问题的简单方法吗?
这是某人的自定义字段集。只有自定义解串器可能有帮助。
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);
}
}