Var*_*har 67 java datetime json jackson
我从ExtJS获得一个日期字符串格式:
"2011-04-08T09:00:00"
当我尝试反序列化此日期时,它会将时区更改为印度标准时间(将时间+5:30添加).这就是我如何反序化日期:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);
Run Code Online (Sandbox Code Playgroud)
这样做也不会改变时区.我仍然在IST得到日期:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);
Run Code Online (Sandbox Code Playgroud)
如何在没有时区麻烦的情况下对日期的日期进行反序列化?
Var*_*har 136
我找到了一个解决方法但是我需要在整个项目中注释每个日期的setter.有没有一种方法可以在创建ObjectMapper时指定格式?
这是我做的:
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并使用以下方法注释每个Date字段的setter方法:
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
Run Code Online (Sandbox Code Playgroud)
小智 55
这对我有用 - 我使用的是杰克逊2.0.4
ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);
Run Code Online (Sandbox Code Playgroud)
wan*_*ngf 13
有一个关于这个主题的好博客:http: //www.baeldung.com/jackson-serialize-dates 使用@JsonFormat看起来是最简单的方法.
public class Event {
public String name;
@JsonFormat
(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
public Date eventDate;
}
Run Code Online (Sandbox Code Playgroud)
除了Varun Achar的回答之外,这是我提出的Java 8变体,它使用java.time.LocalDate和ZonedDateTime而不是旧的java.util.Date类.
public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException {
String string = jsonparser.getText();
if(string.length() > 20) {
ZonedDateTime zonedDateTime = ZonedDateTime.parse(string);
return zonedDateTime.toLocalDate();
}
return LocalDate.parse(string);
}
}
Run Code Online (Sandbox Code Playgroud)