gpt4 book ai didi

java - Jackson @JsonIgnoreProperties 无法在父类(super class)中工作

转载 作者:行者123 更新时间:2023-11-30 05:26:37 34 4
gpt4 key购买 nike

我有一个名为“BaseEntity”的类。从基础实体扩展的其他实体。

基础实体

@MappedSuperclass
public abstract class BaseEntity {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;

@ManyToOne
@JsonIgnoreProperties({"createdBy", "lastModifiedBy", "manager"})
private User createdBy;

private Instant createdDate = Instant.now();

@ManyToOne
@JsonIgnoreProperties({"createdBy", "lastModifiedBy", "manager"})
private User lastModifiedBy;

private Instant lastModifiedDate = Instant.now();

// getters & setters
}

从基础实体扩展的用户实体。

@Entity
public class User2 extends BaseEntity {

private String userName;

@ManyToOne
@JsonIgnoreProperties({"createdBy", "lastModifiedBy", "manager"})
private User manager;

// getters & setters
}

错误当我尝试序列化用户时出现此错误。

org.springframework.http.converter.HttpMessageConversionException:类型定义错误:[简单类型,类a.b.c.d.domain.User];嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidDefinitionException:直接自引用导致循环(通过引用链:java.util.Collections$UnmodifyingRandomAccessList[0]->a.b.c.d.domain.User["createdBy"])

如果我像这样只更改createdBy和lastModifiedBy,它就可以工作。经理用户不会导致错误

    @ManyToOne
@JsonIgnore
private User createdBy;

但是这次 json 不包含任何createdBy 或lastModifiedBy 信息。

{
"id": 2,
"userName": "admin",
"manager": {
"id": 1,
"username": "system"
}
}

我只是想看看这个 json。第一步必须包含createdBy和lastModifiedBy。

{
"id": 2,
"userName": "admin",
"manager": {
"id": 1,
"username": "system"
},
"createdBy": {
"id": 1,
"username": "system"
},
"lastModifiedBy": {
"id": 2,
"username": "admin"
}
}

最佳答案

正确的使用方法是在类级别。这些属性在 JSON 序列化和反序列化中被认为是被忽略的。

示例:-

@JsonIgnoreProperties({ "bookName", "bookCategory" })
public class Book {
@JsonProperty("bookId")
private String id;

@JsonProperty("bookName")
private String name;

@JsonProperty("bookCategory")
private String category;

}

如果您想在字段级别忽略,可以使用@JsonIgnore

关于java - Jackson @JsonIgnoreProperties 无法在父类(super class)中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58445279/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com