提问人:OzanCinci 提问时间:11/13/2023 最后编辑:OzanCinci 更新时间:11/13/2023 访问量:62
Java Spring Boot 无法使用 .json 文件中的 LocalDateTime
Java Spring Boot cannot use LocalDateTime from .json file
问:
我使用模拟 json 数据开发一个应用程序,格式如下:
编辑:我没有在我的项目中使用spring data jpa。
{
"id": 1,
"title": "Video 1",
"duration": "10:30",
"description": "A sample video",
"url": "https://s3.amazonaws.com/example-bucket/video1.mp4",
"createdAt": "2022-11-11T10:08:29.973058478",
"creatorId": 101,
"category": "Technology",
"view": 115,
"like": 23,
"dislike": 5
}
这是我的视频课。
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Video {
private Integer id;
private String title;
private String duration; // as miliseconds
private String description;
private String url;
private String createdAt;
private Integer creatorId;
private String category;
private Integer view;
private Integer like;
private Integer dislike;
}
每当我将创建的 at 更改为 LocalDateTime 类型时,它都会损坏。它说:
Failed to instantiate [ozancinci.video.VideoRepository]: Constructor threw exception
可能是什么问题?只有当我将类型更改为 LocalDateTime 时,它才会中断。当我将其设置为字符串类型时,错误消失了。
我正在寻找 1 小时的解决方案,但我找不到任何可靠的东西。
答:
2赞
Radu Sebastian LAZIN
11/13/2023
#1
你需要告诉与Spring一起使用的JSON库如何解析该字段。createdAt
如果您使用的是 Jackson,那么如果您真的想要,注释可以解决问题,但正如第一条评论所建议的那样,有更好的替代方案,例如 或 也可以与以下内容一起使用:JsonFormat
LocalDateTime
Instant
ZonedDateTime
...
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
private LocalDateTime createdAt;
...
如果你使用的是 GSON,你需要编写一个解串器,如下所示:
class MyDateDeserializer implements JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return LocalDateTime.parse(json.getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));
}
}
然后在你的课堂上,你需要注释你的字段(我省略了任何验证,所以更容易理解):
...
@JsonAdapter(MyDateDeserializer.class)
private LocalDateTime createdAt;
...
我已经很久没有使用GSON了,所以可能有一种更简单的方法,但这也应该有效。
我也不鼓励你使用龙目岛,因为一旦它被卷入一个项目,几乎不可能摆脱。只需让您的 IDE 生成 getter、setter、构造函数、equals 方法、哈希代码等即可。
评论
0赞
OzanCinci
11/15/2023
您好,我正在尝试实现一项动手 Java 任务,该任务是我作为 Jr. Java 开发人员申请的一家公司提供给我的。由于截止日期在您发送答案之前到期,并且当时我找不到任何解决方案,因此我将日期存储为字符串,然后使用解析器进行日期比较以进行排序。请问这种做法有多糟糕?我试图在我的解决方案中用评论行解释它,但我觉得这样做并不适合。(注意:该任务希望我使用 .json 文件作为数据收集,所以我没有使用真正的数据库作为我的解决方案)
评论
java.time.Instant
OffsetDateTime
ZonedDateTime
LocalDateTime
Z
Instant.parse
Instant#toString