File tree Expand file tree Collapse file tree
main/java/com/baeldung/jacksonannotation/format
test/java/com/baeldung/jacksonannotation/format Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .jacksonannotation .format ;
2+
3+ import java .util .Date ;
4+ import com .fasterxml .jackson .annotation .JsonFormat ;
5+
6+ import com .baeldung .jacksonannotation .domain .Person ;
7+
8+ /**
9+ * @author Jay Sridhar
10+ * @version 1.0
11+ */
12+ public class User extends Person {
13+ private String firstName ;
14+ private String lastName ;
15+
16+ @ JsonFormat (shape = JsonFormat .Shape .STRING ,
17+ pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ" )
18+ private Date createdDate ;
19+
20+ public User (String firstName ,String lastName ) {
21+ super (firstName , lastName );
22+ this .createdDate = new Date ();
23+ }
24+
25+ public Date getCreatedDate () {
26+ return createdDate ;
27+ }
28+
29+ @ JsonFormat (shape = JsonFormat .Shape .STRING ,
30+ pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ" ,
31+ locale = "en_GB" )
32+ public Date getCurrentDate () {
33+ return new Date ();
34+ }
35+
36+ @ JsonFormat (shape = JsonFormat .Shape .NUMBER )
37+ public Date getDateNum () {
38+ return new Date ();
39+ }
40+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .jacksonannotation .format ;
2+
3+ import java .util .Date ;
4+
5+ import com .fasterxml .jackson .core .JsonProcessingException ;
6+
7+ import com .fasterxml .jackson .databind .ObjectMapper ;
8+
9+ import org .junit .Test ;
10+
11+ import static io .restassured .path .json .JsonPath .from ;
12+
13+ import static org .assertj .core .api .Assertions .assertThat ;
14+ import static org .assertj .core .data .Percentage .withPercentage ;
15+
16+ /**
17+ * @author Jay Sridhar
18+ * @version 1.0
19+ */
20+ public class JsonFormatTest {
21+
22+ @ Test
23+ public void whenSerializedDateFormat_thenCorrect () throws JsonProcessingException {
24+
25+ User user = new User ("Jay" , "Sridhar" );
26+
27+ String result = new ObjectMapper ().writeValueAsString (user );
28+
29+ // Expected to match: "2016-12-19@09:34:42.628+0000"
30+ assertThat (from (result ).getString ("createdDate" ))
31+ .matches ("\\ d{4}\\ -\\ d{2}\\ -\\ d{2}@\\ d{2}:\\ d{2}:\\ d{2}\\ .\\ d{3}\\ +\\ d{4}" );
32+
33+ // Expected to be close to current time
34+ long now = new Date ().getTime ();
35+ assertThat (from (result ).getLong ("dateNum" ))
36+ .isCloseTo (now , withPercentage (10.0 ));
37+
38+ }
39+ }
You can’t perform that action at this time.
0 commit comments