Summary
我正在尝试解析日期,例如25/Sep/17
因此简单日期格式 https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html注释似乎是@JsonFormat(pattern = "dd/MMM/yy")
。然而,当我尝试解析它时,我得到一个 InvalidFormatException ,其本质是(下面的示例后的完整异常):
Text '25/Sep/17' could not be parsed at index 3
我的日期格式字符串有什么问题?我看不出任何问题。看起来好像不太喜欢Sep
配对MMM
.
我正在使用 Amazon Corretto Java 版本“11.0.5”2019-10-15 LTS
重现示例
package example;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.LocalDate;
public class HelloMapperApp {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) {
MAPPER.registerModule(new JavaTimeModule());
try {
Example example = MAPPER.readValue("{ \"name\": \"example\", \"date\": \"25/Sep/17\"", Example.class);
System.out.println("Deserialised is: " + example);
} catch (Exception e) {
throw new RuntimeException("Could not parse JSON: " + e);
}
}
static class Example {
@JsonProperty
String name;
@JsonProperty
@JsonFormat(pattern = "dd/MMM/yy")
LocalDate date;
@Override
public String toString() {
return String.format("name: %s%ndate: %s", name, date);
}
}
}
完全例外
Exception in thread "main" java.lang.RuntimeException: Could not parse JSON: com.fasterxml.jackson.databind.exc.InvalidFormatException:
Cannot deserialize value of type
`java.time.LocalDate` from String "25/Sep/17": Failed to deserialize java.time.LocalDate:
(java.time.format.DateTimeParseException) Text '25/Sep/17' could not be parsed at index 3
at [Source: (String)"{ "name": "example", "date": "25/Sep/17""; line: 1, column: 30] (through reference chain: example.HelloMapperApp$Example["date"])
at example.HelloMapperApp.main(HelloMapperApp.java:19)
对于格式化程序使用的区域设置,给定的输入可能具有错误的格式。Here https://stackoverflow.com/questions/52572726/datetimeparseexception-on-java-11-but-works-on-java-10是一个类似的帖子,有人遇到了问题Sep
格式化程序期望的位置Sep.
for Locale.CANADA
.
Here https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations and here https://stackoverflow.com/questions/12463049/date-format-mapping-to-json-jackson您可以查看如何设置格式化程序的区域设置。例如。:
@JsonFormat(locale = "en", pattern = "dd/MMM/yy")
仅供参考:您不需要使用LLL
几个月来作为文本。看看日期时间格式化程序 https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html.
数字/文本:如果模式字母的数量为 3 或更多,请使用上面的文本规则。否则请使用上面的编号规则。
当你使用MMM
,即三次M
,格式化程序将隐式使用文本格式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)