Gson - 无法解析的日期错误?

时间:2017-11-28 15:00:56

标签: java json date parsing gson

我有以下JSON和POJO

JSON:

{
      "startDate": "2018-09-18T12:00:00+0000",
      "endDate": "2018-09-18T14:00:00+0000",
      "startDateAsDate": 15372720000000
      "endDateAsDate": 1537279200000
    }

JAVA POJO:

public class ScheduledPeriod implements Comparator<ScheduledPeriod> {

    private String startDate = "";
    private String endDate = "";
    private Date startDateAsDate;
    private Date endDateAsDate;

     public Date getStartDateAsDate() {
        if (startDateAsDate != null) {
            return startDateAsDate;
        }
        try {
            startDateAsDate = (Date) SDF.parseObject(startDate);
            return startDateAsDate;
        } catch (Exception e) {
            return null;
        }
    }

    public Date getEndDateAsDate() {
        if (endDateAsDate != null) {
            return endDateAsDate;
        }
        try {
            endDateAsDate = (Date) SDF.parseObject(endDate);
            return endDateAsDate;
        } catch (Exception e) {
            return null;
        }
    }
}

尝试使用GSON解析JSON:

ScheduledPeriod scheduledPeriod = null;

 try {
            scheduledPeriod = new Gson().fromJson(jsonRequest, new TypeToken<ScheduledPeriod>() {
            }.getType());
        } catch (Exception e) {

        }

我收到错误:

com.google.gson.JsonSyntaxException: 1537272000000
java.text.ParseException: Unparseable date: "1537272000000"

为什么我收到上述错误?日期有效吗?

1 个答案:

答案 0 :(得分:1)

基于this post,您只需为Date注册适配器:

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    return new Date(json.getAsJsonPrimitive().getAsLong());
                }
            }).create();

ScheduledPeriod scheduledPeriod = gson.fromJson(jsonRequest, ScheduledPeriod.class);