【问题标题】:Gson can't parse my json date in java [duplicate]Gson无法在java中解析我的json日期[重复]
【发布时间】: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 我看到了,但就像我说的,我不知道我的格式是什么,我不确定那是输入格式还是其他格式

标签: java json date gson


【解决方案1】:

自纪元以来,您似乎有几毫秒的时间。

建议使用java.time API now in Java 8 而不是SimpleDateFormat

import java.time.Instant;
import java.time.ZonedDateTime;
import java.timeZoneOffset;

// ... 

long epoch = Long.parseLong(jsonElement.getAsString()); // Or if you can do jsonElement.getAsLong()
Instant instant = Instant.ofEpochMilli(epoch);
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); // 2017-03-17T12:11:32Z

但是,无论如何,您不需要 SimpleDateFormat 从 long 值返回 Date

public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
    long epoch = jsonElement.getAsLong();
    return new Date(epoch);
 }

【讨论】:

  • 这只是给了我红线,到处都是Usage of API documented as @since 1.6+jsonElement.getAsLong(); 还不够吗?
  • 足够了,是的。 import 语句位于文件的顶部,因此除非您没有使用 Java 8 进行编译,否则不确定您还做错了什么
  • 导入位于文件顶部它们所属的位置(还有那些红线)
  • 就像我说的,如果你不能导入,那么你就没有针对 Java 8 进行编译
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多