Skip to content

Commit eadf45d

Browse files
jaysridharpivovarit
authored andcommitted
Added demonstration of @jsonformat and associated test. (eugenp#906)
1 parent ba89722 commit eadf45d

2 files changed

Lines changed: 79 additions & 0 deletions

File tree

  • jackson-annotations/src
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
}

0 commit comments

Comments
 (0)