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

Time:06-04

I have a class like below.

@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;
...
}

I get this object via a Rest endpoint. The problem is when the field passPayer and driver objects are equal, in the returning JSON, the driver field contains only the ID (which is just an integer value) and passPayer field has all the object fields.

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

When these fields have different objects, both fields show full details like below.

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

I need both objects to contain data (fields. [id, firstName, lastName, idNo]) whether they are equal or not.

Any clue is appreciated!

CodePudding user response:

This is caused by @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id" ), check the docs. To cite :

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.

Since both fields are referencing the same object, the second one is serialized as a reference to the first object.

In my experience, this annotation is mostly used to deal with circular references, so you can:

  1. remove it, if your use case allows it(no circular references in object)
  2. or you can use DTOs(which is the prefered approach anyway)
  • Related