2

I have the following JSON and 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;
        }
    }
}

Trying to parse JSON using GSON:

ScheduledPeriod scheduledPeriod = null;

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

        }

Error I am getting:

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

Why am I getting the error above? The date is valid?

java123999
  • 6,974
  • 36
  • 77
  • 121
  • 1
    The long cannot be converted to Date directly, you may declare it as long. – Marcos Vasconcelos Nov 28 '17 at 15:04
  • 1
    here is the solution on how to serialize/deserialize them to long: https://stackoverflow.com/a/41979087/304179 – dube Nov 28 '17 at 15:07
  • 1
    See https://stackoverflow.com/questions/5671373/unparseable-date-1302828677828-trying-to-deserialize-with-gson-a-millisecond – RoiG Nov 28 '17 at 15:46
  • Are you using `java.util.Date`? You'll have a much happier time using the [`java.time`](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) package introduced in Java 8, or [Joda Time](http://www.joda.org/joda-time/) if you're not on Java 8 yet. The legacy date classes are seriously deficient. – dimo414 Dec 02 '17 at 05:02

1 Answers1

4

base on this post you just register an adapter for 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);
Amir Azizkhani
  • 1,662
  • 17
  • 30