3 回答
TA贡献1801条经验 获得超16个赞
用 @JsonSerialize(using = CustomSerializer.class)
@Entity(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue
@Column(name = "user_id")
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@JsonSerialize(using = CustomSerializer.class)
@Column(name = "date_of_birth")
private LocalDateTime dateOfBirth;
. . .
}
自定义序列化程序类:
public class CustomSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
//add your custom date parser
gen.writeString(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()+"");
}
}
TA贡献1797条经验 获得超6个赞
如果您不想装饰所有对象,@JsonSerialize可以将对象映射器配置为始终返回 long for LocalDateTime.
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateSerializer());
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateDeserializer());
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
和 de- 和序列化器。
public class LocalDateSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(String.valueOf(value.atZone(ZoneId.systemDefault()).toEpochSecond()));
}
}
public class LocalDateDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(p.getValueAsString())), ZoneId.systemDefault());
}
}
在您的示例中,您使用的出生日期可能是LocalDate.
TA贡献1906条经验 获得超10个赞
为什么不按如下方式存储日期属性:
@Temporal(TemporalType.TIMESTAMP)
private Date date = new Date();
它以毫秒为单位给出日期。将其格式化为所需的输出是应用层的责任。不要在实体本身上做一些注释。
添加回答
举报