import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
public class DateTypeAdapter implements JsonDeserializer<Date> {
private final DateFormat WITH_MILLI_SECOND_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
private final DateFormat WITHOUT_MILLI_SECOND_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public Date deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {
String str = element.getAsString();
if (StringUtils.isEmpty(str) || "null".equals(str)) {
log.info("Empty or 'null' date string");
return null;
}
try {
return WITH_MILLI_SECOND_FORMAT.parse(str);
} catch (Exception e) {
log.info("can't parse to yyyy-MM-dd HH:mm:ss,SSS");
}
try {
return WITHOUT_MILLI_SECOND_FORMAT.parse(str);
} catch (Exception e) {
log.info("can't parse to yyyy-MM-dd HH:mm:ss");
}
return null;
}
public static void main(String[] args) {
String jsonString = "";
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateTypeAdapter())
.serializeNulls()
.create();
YourClass yours = gson.fromJson(jsonString, YourClass.class);
}
}