杰克逊@JsonIgnoreProperties似乎一直都无法正常工作

时间:2019-07-09 14:07:12

标签: spring jpa serialization jackson

我将两个实体映射到以下类别:

@Getter
@Entity
@Table(name = "users")
@JsonIdentityInfo(generator = PropertyGenerator.class,
                  property  = "id")
@SequenceGenerator(name = "id-generator", sequenceName = "seq_users")
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
@NoArgsConstructor(access = PROTECTED)
@RequiredArgsConstructor
public class User extends IdentifiedById {

    @Include
    @NonNull
    @Column(name = "email_address", unique = true)
    private String emailAddress;

    @Setter
    @JsonIgnore
    private String hash;

    @Setter
    private boolean admin;

    @OneToMany(
            mappedBy = "user",
            orphanRemoval = true,
            cascade = ALL
    )
    @JsonIgnoreProperties("user")
    private Set<Cart> carts;

    {
        carts = new HashSet<>(0);
    }
}

@Getter
@Entity
@Table(
        name = "carts",
        uniqueConstraints = @UniqueConstraint(
                columnNames = {
                        "creation_time",
                        "user_id"
                }
        )
)
@JsonIdentityInfo(generator = PropertyGenerator.class,
                  property  = "id")
@SequenceGenerator(
        name = "id-generator",
        sequenceName = "seq_carts"
)
@EqualsAndHashCode(
        callSuper = false
)
@RequiredArgsConstructor
@NoArgsConstructor(access = PROTECTED)
public class Cart extends IdentifiedById {


    @NonNull
    @Column(name = "creation_time")
    private LocalDateTime creationTime;

    @NonNull
    @ManyToOne(cascade = ALL)
    @JoinColumn(
            name = "user_id",
            referencedColumnName = "id"
    )
    @JsonManagedReference
    private User user;


    @Exclude
    @JsonProperty("productStoreQuantities")
    @JsonSerialize(converter = AdditionConverter.class)
    @OneToMany(mappedBy = "cart", orphanRemoval = true, cascade = ALL)
    private Set<Addition> additions;

    {
        additions = new HashSet<>(0);
    }
}

如果我检索一个用户,则其购物车中不包含其引用,对我来说很好。 现在,从其他端点的角度来看,如果一个人请求多个用户,我不想序列化用户及其购物车:

/ api / users-> {“ id”:1,“ emailAddress”:“ test@test.test”,“ admin”:假}

/ api / users / 1-> {“ id”:1,“ emailAddress”:“ test@test.test”,“ admin”:false,“ carts”:[...]} < / strong>

因此,我创建了一个名为Users的包装器类,其中包含用@JsonValue和@JsonIgnoreProperties(“ carts”)注释的用户列表:

@RequiredArgsConstructor
public class Users implements Serializable, List<User> {

    @Delegate
    @JsonValue
    @JsonIgnoreProperties("carts")
    private final List<User> values;
}

我不知道为什么,但是购物车一直在序列化,听说@JsonIgnoreProperties在集合和数组上不起作用,但在我的第一种情况下可以。

1 个答案:

答案 0 :(得分:0)

您应该在类级别使用JsonIgnoreProperties。 这篇文章对此做了很好的解释

https://www.baeldung.com/jackson-ignore-properties-on-serialization