Added demonstration of @JsonFormat and associated test. (#906)
This commit is contained in:
parent
ba89722236
commit
eadf45d628
|
@ -0,0 +1,40 @@
|
||||||
|
package com.baeldung.jacksonannotation.format;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
|
||||||
|
import com.baeldung.jacksonannotation.domain.Person;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Jay Sridhar
|
||||||
|
* @version 1.0
|
||||||
|
*/
|
||||||
|
public class User extends Person {
|
||||||
|
private String firstName;
|
||||||
|
private String lastName;
|
||||||
|
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.STRING,
|
||||||
|
pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
|
||||||
|
private Date createdDate;
|
||||||
|
|
||||||
|
public User(String firstName,String lastName) {
|
||||||
|
super(firstName, lastName);
|
||||||
|
this.createdDate = new Date();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getCreatedDate() {
|
||||||
|
return createdDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.STRING,
|
||||||
|
pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ",
|
||||||
|
locale = "en_GB")
|
||||||
|
public Date getCurrentDate() {
|
||||||
|
return new Date();
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||||
|
public Date getDateNum() {
|
||||||
|
return new Date();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.jacksonannotation.format;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static io.restassured.path.json.JsonPath.from;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.data.Percentage.withPercentage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Jay Sridhar
|
||||||
|
* @version 1.0
|
||||||
|
*/
|
||||||
|
public class JsonFormatTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException {
|
||||||
|
|
||||||
|
User user = new User("Jay", "Sridhar");
|
||||||
|
|
||||||
|
String result = new ObjectMapper().writeValueAsString(user);
|
||||||
|
|
||||||
|
// Expected to match: "2016-12-19@09:34:42.628+0000"
|
||||||
|
assertThat(from(result).getString("createdDate"))
|
||||||
|
.matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
|
||||||
|
|
||||||
|
// Expected to be close to current time
|
||||||
|
long now = new Date().getTime();
|
||||||
|
assertThat(from(result).getLong("dateNum"))
|
||||||
|
.isCloseTo(now, withPercentage(10.0));
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue