importjava.io.IOException;importjava.text.DateFormat;importjava.text.ParseException;importjava.text.ParsePosition;importjava.util.Date;importjava.util.Locale;importcom.google.gson.Gson;importcom.google.gson.JsonSyntaxException;importcom.google.gson.TypeAdapter;importcom.google.gson.TypeAdapterFactory;importcom.google.gson.internal.bind.DateTypeAdapter;importcom.google.gson.internal.bind.util.ISO8601Utils;importcom.google.gson.reflect.TypeToken;importcom.google.gson.stream.JsonReader;importcom.google.gson.stream.JsonToken;importcom.google.gson.stream.JsonWriter;importcom.zxtc.common.utils.StringUtils;public class DateNullAdapter extends TypeAdapter{public static final TypeAdapterFactory FACTORY = newTypeAdapterFactory() {
@SuppressWarnings("unchecked") //we use a runtime check to make sure the ‘T‘s equal
@Override public TypeAdapter create(Gson gson, TypeTokentypeToken) {return typeToken.getRawType() == Date.class ? (TypeAdapter) new DateTypeAdapter() : null;
}
};private finalDateFormat enUsFormat=DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US);private finalDateFormat localFormat=DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT);
@Overridepublic Date read(JsonReader in) throwsIOException {if (in.peek() ==JsonToken.NULL) {
in.nextNull();return null;
}
String jsonStr=in.nextString();if(StringUtils.isBlank(jsonStr)) {return null;
}else{returndeserializeToDate(jsonStr);
}
}private synchronizedDate deserializeToDate(String json) {try{returnlocalFormat.parse(json);
}catch(ParseException ignored) {
}try{returnenUsFormat.parse(json);
}catch(ParseException ignored) {
}try{return ISO8601Utils.parse(json, new ParsePosition(0));
}catch(ParseException e) {throw newJsonSyntaxException(json, e);
}
}
@Overridepublic synchronized void write(JsonWriter out, Date value) throwsIOException {if (value == null) {
out.nullValue();return;
}
String dateFormatAsString=enUsFormat.format(value);
out.value(dateFormatAsString);
}
}