Jackson - Serialize entity with self-reference

前端 未结 2 562
忘掉有多难
忘掉有多难 2021-01-25 20:35

I have the following entity:

@Entity
@Table(name = \"registry_entry\")
@JsonIgnoreProperties(ignoreUnknown = true)
public class RegistryEntry extends GenericEnti         


        
2条回答
  •  无人及你
    2021-01-25 21:33

    Jackson supports @JsonIdentityInfo. This is does what you're describing: adding this annotation to a class will make all instances of that class be serialized with an additional ID field, and the next time the same instance needs to be serialized the value of that ID field will be written instead of the whole object.

    However, note that this is not standard JSON. In general, JSON format is usually used because it's widely supported by many libraries. Using this feature will likely create additional problems for your API clients.

    The more universally compatible approach is to serialize the self-referenced object without its self-reference field:

    public class RegistryEntry {
            @JsonIgnoreProperties("relatedRegistryEntries")
            private List relatedRegistryEntries;
    }
    

提交回复
热议问题