Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON serialization strategy for dates

The problem I am having is that I have some consumers that are Java and some that are browsers. My target browsers are IE7+ (json3 for IE7 only) & Chrome.

For a browser I wish to have the date deserialize to a Date JavaScript object (using the JSON.parse() method. For a Java consumer I wish to deserialize to a java.util.Date Java object.

Given that I can't change anything on the browser side. I have to do serialize the messages to something like this:

{ myDate: new Date(<EPOCH HERE>) }

Which of course will cause a problem for Java deserializer. However, I am hoping there is something I can do with Gson to make this work...amy ideas?

Or should I take a different strategy altogether?

like image 678
Cheetah Avatar asked May 07 '26 21:05

Cheetah


1 Answers

I usually use the annotation @JsonSerialize and @JsonDeserialize to deal with this problem. I also use ISO8601 format as a standard for our REST API dates.

@JsonSerialize(using=JsonDateSerializer.class)
@JsonDeserialize(using=JsonDateDeserializer.class)
private Date expiryDate;

JsonDateSerializer class

@Component
public class JsonDateSerializer extends JsonSerializer<Date>
{
    // ISO 8601
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException
    {
        String formattedDate = dateFormat.format(date);
        gen.writeString(formattedDate);
    }
}

JsonDateDeserializer class

@Component
public class JsonDateDeserializer extends JsonDeserializer<Date>
{
    // ISO 8601
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException
    {
        try
        {
            return dateFormat.parse(jsonParser.getText());
        }
        catch (ParseException e)
        {
            throw new JsonParseException("Could not parse date", jsonParser.getCurrentLocation(), e);
        }
    }
}
like image 53
TheEwook Avatar answered May 09 '26 10:05

TheEwook