【发布时间】:2017-03-20 16:21:45
【问题描述】:
我正在尝试对使用 rest 的 java-ee 应用程序进行一些测试,但是当我尝试使用 gson 格式化一些 json 时出现以下错误:
java.text.ParseException: Failed to parse date ["1489752692000']: Invalid time zone indicator '9'
这发生在我使用 Gson gson = new Gson(); 初始化我的 Gson 时,我在 StackOverflow 上找到了 this question,解决方案是创建一个自定义 DateDeseriliazer 类并像这样初始化:
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonDateFormatter()).create();
这是我的 DateDeserializer 类的版本:
public class GsonDateFormatter implements JsonDeserializer<Date> {
private final DateFormat dateFormat;
public GsonDateFormatter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
}
public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
但这只会将错误消息更改为:
java.text.ParseException: Unparseable date: "1489752692000"
所以我现在不太确定如何解决这个问题,我希望有人可以帮助我。
提前致谢。
【问题讨论】:
-
也许只是
new Date(jsonElement.getAsLong())? -
1489752692000显然不是yyyy-MM-dd'T'HH:mm:ss'Z'的格式,那你为什么给那个格式呢? -
@cricket_007 因为我不确定该放什么格式,而另一篇帖子使用了该格式
-
再次阅读另一篇文章。查看 JSON 字符串中的日期。
-
@cricket_007 我看到了,但就像我说的,我不知道我的格式是什么,我不确定那是输入格式还是其他格式