【问题标题】:JSON serialization with relation and @JsonIdentityInfoJSON 序列化与关系和@JsonIdentityInfo
【发布时间】:2018-04-05 00:22:32
【问题描述】:

我有两个班级:

@Entity
@JsonIdentityInfo(
    generator = ObjectIdGenerators.PropertyGenerator.class,
    property = "id")
public class Client extends AbstractEntity {

    ...

    @OneToMany(mappedBy = "client", fetch = FetchType.EAGER)
    @Cascade(org.hibernate.annotations.CascadeType.PERSIST)
    private Set<Patient> patients = new HashSet<>();

还有:

@Entity
@JsonIdentityInfo(
    generator = ObjectIdGenerators.PropertyGenerator.class,
    property = "id")
 public class Patient extends AbstractLastOpenedDateEntity implements Serializable {

    ...

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "client_id")
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    private Client client;

假设我有一个患者名单: - 患者 A(来自客户 1) - 患者 B(来自客户 1) -患者 C(来自客户 2) 当我使用 Jackson 序列化它时我想要什么:

[
   { id: A, client: { id: 1, patients: [A,B]}  },
   { id: B, client: { id: 1, patients: [A,B]}  },
   { id: C, client: { id: 2, patients: [C]}  },
]

但这是我得到的:

[
   { id: A, client: { id: 1, patients: [ A , { id: B, client: { id: 1, patients: [A,B]}]}  },
   B,
   { id: C, client: { id: 2, patients: [C]}  },
]

Jackson 似乎只是第一次进行“完整序列化”,然后才进行“短序列化”(id)。 我希望对“根”json 级别的优先级进行完全序列化。

谢谢!

【问题讨论】:

    标签: java json spring-boot serialization jackson


    【解决方案1】:

    在您的患者集中使用 @JsonIdentityReference(alwaysAsId = true) 注释。 问题是@JsonIdentityInfo 只会完全序列化一个 在整个序列化过程中默认出现一个对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2013-11-20
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多