-3

I'm trying to make some test for a java-ee application that uses rest, but when I tried to format some json with gson I got the following error:

java.text.ParseException: Failed to parse date ["1489752692000']: Invalid time zone indicator '9'

This happened when I initialized my Gson with Gson gson = new Gson();, I found this question on StackOverflow where the solution was to make a custom DateDeseriliazer class and intialize like this:

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonDateFormatter()).create();

Here is my version of the DateDeserializer class:

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);
        }
    }
}

But this only changes the error message to:

java.text.ParseException: Unparseable date: "1489752692000"

So I'm not quite sure how to solve this now and I hope someone can help me with this.

Thanks in advance.

Community
  • 1
  • 1
Dennis van Opstal
  • 1,294
  • 1
  • 22
  • 44

1 Answers1

2

You have what appears to be milliseconds since epoch.

It's recommended to use java.time API now in Java 8 instead of 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

But, in any case, you don't need SimpleDateFormat to return a Date from a long value.

public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
    long epoch = jsonElement.getAsLong();
    return new Date(epoch);
 }
Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245