摘要
我试图解析的日期,如25/Sep/17
因此SimpleDateFormat的注释似乎是@JsonFormat(pattern = "dd/MMM/yy")
。然而,当我尝试分析这个,我得到一个InvalidFormatException其中的本质是(下面的例子经过充分的除外):
Text '25/Sep/17' could not be parsed at index 3
有什么不对我的日期格式字符串?我看不出任何问题。它看起来像它不喜欢的Sep
搭配MMM
。
我使用亚马逊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)
这可能是给定的输入有由格式所使用的语言环境的格式不正确的情况。这是一个类似的帖子里有人有一个问题Sep
格式化预计其中Sep.
的Locale.CANADA
。
@JsonFormat(locale = "en", pattern = "dd/MMM/yy")
FYI:您不需要使用LLL
数月为文本。有一看DateTimeFormatter。
号码/文字:如果模式字母的数量为3或更大,使用上面的文字规定。否则,使用上面的编号规则。
当您使用MMM
,即三次M
,格式化将隐式使用文本格式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句