我想我的所有Gson DateDeserializer设置都没问题,但它会引发错误Unparseable date
提前感谢。
private Gson getGson() {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new DateDeserializer());
builder.setPrettyPrinting();
return builder.create();
}
DateDeserializer:
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import timber.log.Timber;
public class DateDeserializer implements JsonDeserializer<Date> {
private static final String TAG = "DateDeserializer";
private static final String[] DATE_FORMATS = new String[]{
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ",
"yyyy-MM-dd'T'HH:mm:ssZ",
"MMM d, yyyy hh:mm:ss a",// Aug 29, 2016 09:11:08 AM
"MMM d, yyyy HH:mm:ss",//Aug 29, 2016 16:11:08
};
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
Timber.d(e.getMessage());
}
}
throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
}
logcat的:
D/DateDeserializer: Unparseable date: "2016-10-19T13:27:58+05:30" (at offset 19)
D/DateDeserializer: Unparseable date: "2016-10-27T06:32:00+00:00" (at offset 19)
D/DateDeserializer: Unparseable date: "2016-10-27T06:32:00+00:00" (at offset 19)
D/DateDeserializer: Unparseable date: "2016-10-27 06:32:00+00:00" (at offset 10)
D/DateDeserializer: Unparseable date: "2016-10-27 06:32:00+00:00" (at offset 10)
D/DateDeserializer: Unparseable date: "2016-10-27 06:32:00+00:00" (at offset 0)
D/DateDeserializer: Unparseable date: "2016-10-27 06:32:00+00:00" (at offset 0)
W/System.err: com.google.gson.JsonParseException: Unparseable date: "2016-10-27 06:32:00+00:00". Supported formats: [yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ, yyyy-MM-dd'T'HH:mm:ssZ, MMM d, yyyy hh:mm:ss a, MMM d, yyyy HH:mm:ss]
答案 0 :(得分:0)
即使没有发生异常,此方法也会抛出异常。这个方法应该是这样的:
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
Timber.d(e.getMessage());
}
}
return null;
}
现在为此。格式将匹配,该日期将被返回。如果与任何格式不匹配,则返回null。