java - @JsonSerialize 没有从控制器 springboot 2.2.4 转换我的日期格式
问题描述
我有带日期的模型(ModelX)
@Entity
class ModelX
....
@JsonSerialize(using = DateSerializer.class)
private Long date;
日期序列化器
public class JsonDateSerializer extends JsonSerializer<DateTime>
{
private static DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
@Override
public void serialize(DateTime value, JsonGenerator gen,
SerializerProvider arg2)
throws IOException, JsonProcessingException {
gen.writeString(formatter.print(value));
}
}
我的控制器
@RestController
public class XC {
@GetMapping(value = "/get/{main_key}"
public get ModelX get(@PathVariable("main_key") String main_key) {
return repository.get(main_key);
}
}
提取有效,但我的日期很长,但我想要一个日期“dd/MM/yyyy”
解决方案
使用 JSON 自定义序列化程序,您可以格式化 LONG 日期
@Entity
class ModelX
....
@JsonSerialize(using = JsonDateCustom.class)
private Long date;
自定义序列化器
@Component
public class JsonDateCustom extends JsonSerializer<Long> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
@Override
public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
String formattedDate = dateFormat.format(value);
gen.writeString(formattedDate);
}
}
推荐阅读
- php - 获取 Laravel 中的所有关系多对多多态
- vba - 如何让多个用户使用 MS Access 前端和 MariaDB 从同一个表中选择不同的记录?
- swift - JSONSerialize 在不同的 json 对象上
- flutter - 找不到 MediaQuery 祖先?
- stripe-payments - 是否有必要创建所有帐户,人员,客户才能进行条带式交易?
- c++ - 架构 x86_64 的未定义符号:链接器错误
- iis - iis url 重写有或没有查询
- node.js - POST 在 ProxyPass 之后变为 GET
- android - Ionic Capacitor firebase 推送通知,错误:此过程中未初始化默认 FirebaseApp
- javascript - 如何从谷歌表格制作依赖下拉列表?