jpa 将JSON值反序列化为类型时出错:类java.时间.年月

rks48beu  于 2022-11-14  发布在  Java
关注(0)|答案(1)|浏览(134)

雅加达EE

@Entity(name = "Book")
@Table(name = "book")
public class Book {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String isbn;

    private String title;

    @Column(name = "published_on", columnDefinition = "date")
    @Convert(converter = YearMonthDateAttributeConverter.class)
    private YearMonth publishedOn;

    // Getters and setters omitted for brevity
}

我只想插入年份和月份,我使用的是JakartaEE Jsonb。Localdate工作正常,但我也必须插入日期。我不习惯使用Jackson。

JEE JSON Binding

public class Book {

    public String isbn;
    public String title;
    public YearMonth publishedOn;

}

public static void main(String[] args) {

        // Create a book instance
        Book book = new Book();
        book.isbn = "123";
        book.title = "Advanced JPA and Hibernate";
        book.publishedOn = YearMonth.of(2022, 9);

        // Create Jsonb and serialize
        Jsonb jsonb = JsonbBuilder.create();
        var result = jsonb.toJson(book);
}
owfi6suc

owfi6suc1#

我通过创建YearMonthTypeAdapter来实现JsonAdapter<YearMonth, String>类,然后覆盖下面的方法,找到了一个解决方案:
1.

String adaptToJson(YearMonth date) return date.toString;
YearMonth adaptFromJson(String string) return YearMonth.parse(string);

相关问题