[BAEL-2533] Formatting JSON Dates in Spring Boot (#6313)

* [BAEL-2533] formatting json date output in spring boot

* [BAEL-2533] removed unused import
This commit is contained in:
Marko Previsic 2019-02-11 04:22:34 +01:00 committed by maibin
parent ecabba42ef
commit e6fc0bd94d
11 changed files with 561 additions and 0 deletions

View File

@ -0,0 +1,70 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Contact {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime lastUpdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public LocalDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(LocalDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Contact() {
}
public Contact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.jsondateformat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ContactApp {
public static void main(String[] args) {
SpringApplication.run(ContactApp.class, args);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.format.DateTimeFormatter;
@Configuration
public class ContactAppConfig {
private static final String dateFormat = "yyyy-MM-dd";
private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
@Bean
@ConditionalOnProperty(value = "spring.jackson.date-format", matchIfMissing = true, havingValue = "none")
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.simpleDateFormat(dateTimeFormat);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
}
};
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.jsondateformat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping(value = "/contacts")
public class ContactController {
@GetMapping
public List<Contact> getContacts() {
List<Contact> contacts = new ArrayList<>();
Contact contact1 = new Contact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
Contact contact2 = new Contact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
Contact contact3 = new Contact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/javaUtilDate")
public List<ContactWithJavaUtilDate> getContactsWithJavaUtilDate() {
List<ContactWithJavaUtilDate> contacts = new ArrayList<>();
ContactWithJavaUtilDate contact1 = new ContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
ContactWithJavaUtilDate contact2 = new ContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
ContactWithJavaUtilDate contact3 = new ContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plain")
public List<PlainContact> getPlainContacts() {
List<PlainContact> contacts = new ArrayList<>();
PlainContact contact1 = new PlainContact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact2 = new PlainContact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact3 = new PlainContact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plainWithJavaUtilDate")
public List<PlainContactWithJavaUtilDate> getPlainContactsWithJavaUtilDate() {
List<PlainContactWithJavaUtilDate> contacts = new ArrayList<>();
PlainContactWithJavaUtilDate contact1 = new PlainContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact2 = new PlainContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact3 = new PlainContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class ContactWithJavaUtilDate {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date lastUpdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public ContactWithJavaUtilDate() {
}
public ContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.jsondateformat;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class PlainContact {
private String name;
private String address;
private String phone;
private LocalDate birthday;
private LocalDateTime lastUpdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public LocalDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(LocalDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
public PlainContact() {
}
public PlainContact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class PlainContactWithJavaUtilDate {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date lastUpdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public PlainContactWithJavaUtilDate() {
}
public PlainContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@ -6,6 +6,7 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import java.util.Date;
@Entity
@Table(name = "person")
@ -25,6 +26,8 @@ public class Employee {
@Size(min = 3, max = 20)
private String name;
private Date birthday;
public Long getId() {
return id;
}

View File

@ -73,3 +73,5 @@ chaos.monkey.watcher.repository=false
#Component watcher active
chaos.monkey.watcher.component=false
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Europe/Zagreb

View File

@ -0,0 +1,96 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = ContactApp.class)
@TestPropertySource(properties = {
"spring.jackson.date-format=yyyy-MM-dd HH:mm:ss"
})
public class ContactAppIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/contacts", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenJsonFormatAnnotationAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/contacts/javaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test(expected = DateTimeParseException.class)
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenNotApplyFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = ContactApp.class)
public class ContactAppWithObjectMapperCustomizerIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
}