package cn.superdesk.uniorder.common;

import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author carl
 */
@Slf4j
public class GSONDateUtil implements JsonSerializer<Date>, JsonDeserializer<Date> {


	@Override
	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {

		SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date             date = null;

		try {
			date = sdf.parse(json.getAsJsonPrimitive().getAsString());
		} catch (ParseException e) {

			log.error("GSONDateUtil deserialize error." + e.getMessage());
		}

		return date;

	}


	@Override
	public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return new JsonPrimitive(sdf.format(src));
	}

}
