This article mainly introduces how to solve the formatting problem of SpringMVC returning Java8 time JSON data. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Sometimes the @ResponseBody annotation is used when returning a response in JSON format in Spring MVC, but it will be very troublesome when processing time in java8. Generally, the HTTPMessageConverter we use is MappingJackson2HttpMessageConverter, the time format it returns by default is this:
"startDate" : { "year" : 2010, "month" : "JANUARY", "dayOfMonth" : 1, "dayOfWeek" : "FRIDAY", "dayOfYear" : 1, "monthValue" : 1, "hour" : 2, "minute" : 2, "second" : 0, "nano" : 0, "chronology" : { "id" : "ISO", "calendarType" : "iso8601" } }
But we will not return this to the front end, and we want to return it for LocalDate The format is 2016-11-26, and the format that LocalDateTime wants to return is data such as 2016-11-26 21:04:34. Through project research and consulting relevant information, here are two ways to implement it in personal research.
Solution 1:
If it is a maven project, introduce the following jar package into the pom:
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.8.5</version> </dependency>
Then add a @JsonSerializer annotation on the get function of the POJO field you want to JSONize, as follows
import com.fasterxml.jackson.annotation.JsonFormat; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") public LocalDateTime getBirthday() { return this.loginTime; } @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") public LocalDateTime getLastLoginTime() { return this.loginTime; }
The advantage of this method is that different display methods can be set for specific domain types. However, the advantage is also a disadvantage, because each date attribute must be added manually. In fact, the date attribute is generally necessary, and additional jsr310 needs to be introduced. jar package.
Solution 2:
Inherit ObjectMapper to return json string. MappingJackson2HttpMessageConverter mainly uses ObjectMapper to return json strings. Here we write a JsonUtil class, obtain the ObjectMapper to register the corresponding JsonSerializer
/** * json处理工具类 * * */ @Component public class JsonUtil { private static final ObjectMapper mapper; public ObjectMapper getMapper() { return mapper; } static { mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(LocalDate.class, new LocalDateSerializer()); module.addSerializer(LocalTime.class, new LocalTimeSerializer()); module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer()); mapper.registerModule(module); } public static String toJson(Object obj) { try { return mapper.writeValueAsString(obj); } catch (Exception e) { throw new RuntimeException("转换json字符失败!"); } } public <T> T toObject(String json, Class<T> clazz) { try { return mapper.readValue(json, clazz); } catch (IOException e) { throw new RuntimeException("将json字符转换为对象时失败!"); } } } class LocalDateSerializer extends JsonSerializer<LocalDate> { private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Override public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(dateFormatter.format(value)); } } class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Override public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(dateTimeFormatter.format(value)); } } class LocalTimeSerializer extends JsonSerializer<LocalTime> { private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); @Override public void serialize(LocalTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(timeFormatter.format(value)); } }
Then in the springmvc configuration file, change
<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper" value="#{jsonUtil.mapper}" /> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
Then several date and time types in java8 can be displayed normally and friendly. The advantage is that types such as date and time are managed globally and uniformly, but the disadvantage is that a certain field in the POJO is specially processed.
The above is a detailed explanation of how to solve the formatting problem of SpringMVC returning Java8 time JSON data. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!