我的服务器JSON返回两种不同类型的DateFormat."MMM dd,yyyy"和"MMM dd,yyyy HH:mm:ss"
当我使用以下内容转换JSON时,它很好:
Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy").create();
Run Code Online (Sandbox Code Playgroud)
但是,当我想要详细的日期格式并将其更改为此时,它会抛出异常com.google.gson.JsonSyntaxException:2013年3月21日
Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy HH:mm:ss").create();
Run Code Online (Sandbox Code Playgroud)
有没有办法让gson为其Json转换处理两个不同的DateFormat?
基本上我有一个领域
private LocalDateTime date;
Run Code Online (Sandbox Code Playgroud)
从String解析.它提供的工作正常,String在末尾附加时间,但如果没有则会抛出异常.
DateTimeFormatter formatter = null;
if (value.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}")) {
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
} else if (value.matches("\\d{4}-\\d{2}-\\d{2}")) {
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
}
// Throws an exception for pattern "yyyy-MM-dd"
date = LocalDateTime.parse(value, formatter);
Run Code Online (Sandbox Code Playgroud)
而异常本身:
java.time.format.DateTimeParseException: Text '2000-06-29' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2000-06-29 of type java.time.format.Parsed
at pl.empirica.swissborg.service.util.CsvBeanUtils.copyList(CsvBeanUtils.java:75) ~[classes/:na]
at pl.empirica.swissborg.service.csv.CsvReaderService.persistCsvData(CsvReaderService.java:101) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_91]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_91] …Run Code Online (Sandbox Code Playgroud)