Gson can';t在java中解析我的json日期

Gson can';t在java中解析我的json日期,java,json,date,gson,Java,Json,Date,Gson,我正在尝试对使用rest的java ee应用程序进行一些测试,但当我尝试使用gson格式化一些json时,出现了以下错误: java.text.ParseException:未能分析日期[“1489752692000]”:无效的时区指示器“9” 当我用Gson Gson=new Gson();初始化我的Gson时,我发现在StackOverflow上,解决方案是创建一个定制的DateDeserilizer类并初始化如下: Gson gson = new GsonBuilder().registe

我正在尝试对使用rest的java ee应用程序进行一些测试,但当我尝试使用gson格式化一些json时,出现了以下错误:

java.text.ParseException:未能分析日期[“1489752692000]”:无效的时区指示器“9”

当我用
Gson Gson=new Gson();
初始化我的Gson时,我发现在StackOverflow上,解决方案是创建一个定制的DateDeserilizer类并初始化如下:

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);
        }
    }
}
公共类GsonDateFormatter实现JsonDeserializer{
私人最终日期格式日期格式;
公共GsonDateFormatter(){
dateFormat=新的简化格式(“yyyy-MM-dd'T'HH:MM:ss'Z'”;
dateFormat.setTimeZone(TimeZone.getTimeZone(“CET”));
}
公共同步日期反序列化(JsonElement JsonElement,类型类型,JSONESerializationContext JSONESerializationContext){
试一试{
return dateFormat.parse(jsonElement.getAsString());
}捕获(解析异常){
抛出新的JsonParseException(e);
}
}
}
但这只会将错误消息更改为:

java.text.ParseException:无法解析的日期:“1489752692000”

所以我现在不太确定如何解决这个问题,我希望有人能帮我解决这个问题


提前感谢。

您拥有的似乎是自epoch以来的毫秒数

建议使用而不是
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

但是,在任何情况下,都不需要从长值返回日期

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

可能只是
新日期(jsonElement.getAsLong())
1489752692000
显然不是格式
yyyy-MM-dd'HH:MM:ss'Z'
,那么你为什么要给出这种格式呢?@cricket_007因为我不确定放在那里的是什么格式,而另一篇文章使用了这种格式。请再次阅读另一篇文章。看看JSON字符串中的日期。@cricket_007我看到了,但正如我所说,我没有看到知道我的格式是什么,我不确定那是输入格式还是其他格式。这只会让我到处都是红线,上面写着
API的用法被记录为@since 1.6+
,而不是
jsonElement.getAsLong()
足够?足够了,是的。导入语句位于文件顶部,因此不确定您还有什么地方出错,除非您不是使用Java 8编译。导入位于文件顶部的位置(还有那些红线),如我所说,如果您不能导入,那么您就不是针对Java 8编译