Wednesday, 7 April 2021

@JsonFormat on Getter

 @Jsonformat is an annotation belong to package Jackson-databind

It is used on a Getter method to format how the Date instance is serialized.  By default, a Date instance is serialized as a number ref. to the begging of the time counting. 

As using @JsonFormat, the time output is formatted ref. to a default time-zone or a locale. Normally it is the GMT time zone.  


@Getter
@Setter
@AllArgsConstructor
@Builder
public class RoomReservation {
private Long roomId;
private Long guestId;
private String roomName;
private String roomNumber;
private String firstName;
private String lastName;

@Getter(AccessLevel.NONE)
private Date date;

@JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING, timezone = "Europe/Copenhagen")
public Date getDate() {
return date;
}

}





Thursday, 1 April 2021

Get List of Objects via RestTemplate

After compiling, List<T> aList,  generic type parameter will be erased and replaced by an Object type. That is a  common Java generic operation. However, for a deserialization process, an Object type instance is too general to re-build. You may solve this by using Array or ParameterizedTypeReference interface.


 using Array instance instead of Collection of Generics

@Test
@Sql("classpath:testdata.sql")
@Sql(value = "classpath:deleteTestData.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
void testFindListCustomerByArray() {
URI uri = builder.build().toUri();

ResponseEntity<CustomerDto[]> response = this.template.getForEntity(uri, CustomerDto[].class);

CustomerDto[] customerDtoList = response.getBody();
CustomerDto[] emptyArray = {};

List<String> firstNames = Arrays.asList("Mike", "Mia");
boolean matched = Arrays.stream(customerDtoList != null ? customerDtoList : emptyArray)
.map(c -> c.getFirstName()).collect(toList()).equals(firstNames);

assertAll(
() -> assertThat(customerDtoList).hasSize(2),
() -> assertThat(matched).isTrue()
);
}


 using ParamterizedTypeReference Interface

@Test
@Sql("classpath:testdata.sql")
@Sql(value = "classpath:deleteTestData.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
void testFindAllCustomers() {
URI uri = builder.build().toUri();

//this.template.getForEntity(uri, CustomerDto[].class);
ResponseEntity<List<CustomerDto>> response = this.template.exchange(uri, HttpMethod.GET, null,
new ParameterizedTypeReference<List<CustomerDto>>() {
});

List<CustomerDto> customerDtoList = response.getBody();

List<String> firstNames = Arrays.asList("Mike", "Mia");
boolean matched = customerDtoList.stream().map(c -> c.getFirstName()).collect(toList()).equals(firstNames);

assertAll(
() -> assertThat(customerDtoList).hasSize(2),
() -> assertThat(matched).isTrue()
);
}

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...