JSON returns 一个字段有 ID,另一个字段有完整的对象,当两个对象相同时

JSON returns one field with ID and other field with full object, when both objects are same

我有一个 class 如下所示。

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Entity
@Table( name = "hires", indexes = { @Index( name = "idx_hire_date", columnList = "date DESC" ) }, uniqueConstraints = {
    @UniqueConstraint( columnNames = { "vehicle_id", "po_number" } ) } )
@DynamicUpdate
@JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id" )
public class Hire implements Serializable {

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
int id;

@OneToOne( targetEntity = Driver.class, fetch = FetchType.EAGER )
@JoinColumn( name = "pass_payer", referencedColumnName = "id", nullable = true )
Driver passPayer;

@OneToOne( targetEntity = Driver.class, fetch = FetchType.EAGER )
@JoinColumn( name = "driver_id", referencedColumnName = "id", nullable = true )
Driver driver;
...
}

我通过 Rest 端点获取此对象。 问题是当字段 passPayerdriver 对象相等时,在返回的 JSON 中,driver 字段仅包含 ID(这只是一个整数值)并且 passPayer 字段包含所有对象字段。

"passCost": 300.0,
        "passPayer": {
            "id": 9,
            "firstName": "XXXX",
            "lastName": "XXXXXX",
            "idNo": "000000000000"
        },
        "driver": 9,
        "driverSalary": xxxx.xx, 

当这些字段具有不同的对象时,两个字段都会显示如下所示的完整详细信息。

"passCost": 300.0,
        "passPayer": {
            "id": 9,
            "firstName": "XXXX",
            "lastName": "XXXXXX",
            "idNo": "000000000000"
        },
        "driver": {
            "id": 4,
            "firstName": "YYYYYY",
            "lastName": "YYYYYYY",
            "idNo": "10101010101"
        },
        "driverSalary": 00000.00,

我需要两个对象都包含数据(字段。[id, firstName, lastName, idNo]),无论它们是否相等。

感谢任何线索!

这是@JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id" )造成的,检查docs。引用:

Annotation used for indicating that values of annotated type or property should be serializing so that instances either contain additional object identifier (in addition actual object properties), or as a reference that consists of an object id that refers to a full serialization.

由于两个字段都引用同一个对象,因此第二个字段被序列化为对第一个对象的引用。

根据我的经验,这个注解多用于处理循环引用,所以你可以:

  1. 删除它,如果你的用例允许它(对象中没有循环引用)
  2. 或者您可以使用 DTO(无论如何这是首选方法)