I am using Spring Boot + Spring data Redis
example to save Date into the Redis Cache. Although I used @DateTimeFormat @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
, but still persistance happening is long value. Look like its a millisecond.
Can somebody guide if I need to set extra configurations to persist date like yyyy-MM-dd
.
HGETALL users:1
1) "_class"
2) "com.XXX.entity.User"
3) "userId"
4) "1"
5) "name"
6) "John"
7) "createdDate"
8) "1542043247352"
Entity classes:
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("users")
public class User {
@Id
private Long userId;
private String name;
@DateTimeFormat
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date createdDate;
private List<Group> groups;
}
UPDATE-1:: As per suggestion I implemented, but still not working CustomDateSerializer.java
@Component
public class CustomDateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
Custom Interface
@Retention(RetentionPolicy.RUNTIME)
public @interface MyJsonFormat {
String value();
}
Model class
@MyJsonFormat("dd.MM.yyyy")
@JsonSerialize(using = CustomDateSerializer.class)
private Date createdDate;
By Using Custom Serializer, this can be solved. Ref @https://kodejava.org/how-to-format-localdate-object-using-jackson/#comment-2027
public class LocalDateSerializer extends StdSerializer<LocalDate> {
private static final long serialVersionUID = 1L;
public LocalDateSerializer() {
super(LocalDate.class);
}
@Override
public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException {
generator.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}
POJO:
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate createdDate;