问题
have trouble in LocalDateTime(Java 8) Formatting in Spring MVC framework
my VO is like under code
in mySQL w_date field is DATETIME and recode like "2015-12-25 23:18:22"
public class HistoryBoard {
@JsonFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
private LocalDateTime w_date;
public LocalDateTime getW_date() {
return w_date;
}
public HistoryBoard setW_date(String w_date) {
DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
this.w_date = LocalDateTime.parse(w_date, sdf);
return this;
}
}
add maven dependency
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.5.3</version>
</dependency>
and add @JsonFormat(pattern="yyyy-MM-dd")
in field value w_date
but still json get Object like
"w_date":{"dayOfMonth":25,"dayOfWeek":"FRIDAY","month":"DECEMBER","year":2015,"dayOfYear":359,"monthValue":12,"hour":23,"minute":18,"second":22,"nano":0,"chronology":{"id":"ISO","calendarType":"iso8601"}
json page Controller code
@RequestMapping(value = "/listJson.do")
public @ResponseBody Object listJson(Map<String, Object> commandMap, ModelMap model) throws Exception {
List<HistoryBoard> list = boardService.selectBoardList(commandMap);
return list;
}
回答1:
A similar question is answered here. You may have to add @JsonSerialize(using = LocalDateTimeSerializer.class)
to your field.
You can also create a custom serializer like below:
public class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime>{
@Override
public void serialize(LocalDateTime dateTime, JsonGenerator generator, SerializerProvider sp)
throws IOException, JsonProcessingException {
String formattedDateTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
generator.writeString( formattedDateTime);
}
}
and use that custom serializer in your LocalDateTime field:
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
private LocalDateTime w_date;
来源:https://stackoverflow.com/questions/34464156/json-string-from-localdatetimejava-8-in-spring-mvc