2015-11-02 83 views
6

嵌套的對象我有一個項目,該項目使用對象的一些ORM映射交易(也有一些@OneToMany關係等)。春天開機JPA - JSON而不一對多關係

我使用REST接口來處理這些對象和Spring JPA以在API中管理它們。

這是我的POJO中的一個例子:

@Entity 
public class Flight { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private long id; 
    private String name; 
    private String dateOfDeparture; 
    private double distance; 
    private double price; 
    private int seats; 

    @ManyToOne(fetch = FetchType.EAGER) 
    private Destination fromDestination; 

    @ManyToOne(fetch = FetchType.EAGER) 
    private Destination toDestination; 

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "flight") 
    private List<Reservation> reservations; 
} 

發出請求的時候,我必須指定在JSON的一切:

{ 
    "id": 0, 
    "reservations": [ 
    {} 
    ], 
    "name": "string", 
    "dateOfDeparture": "string", 
    "distance": 0, 
    "price": 0, 
    "seats": 0, 
    "from": { 
    "id": 0, 
    "name": "string" 
    }, 
    "to": { 
    "id": 0, 
    "name": "string" 
    } 
} 

我喜歡什麼,實際上是指定引用對象的id而不是它們的整個身體,如下所示:

{ 
    "id": 0, 
    "reservations": [ 
    {} 
    ], 
    "name": "string", 
    "dateOfDeparture": "string", 
    "distance": 0, 
    "price": 0, 
    "seats": 0, 
    "from": 1, 
    "to": 2 
} 

這是甚至是possi竹葉提取?有人能給我一些關於如何做到這一點的見解嗎?我只找到如何做相反的教程(我已經有了解決方案)。

+0

你可以嘗試找到這個有用的 - http://wiki.fasterxml.com/JacksonFeatureObjectIdentity – VadymVL

回答

14

是的,這是可能的。

爲此,你應該使用對傑克遜的註釋到您的實體模型:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") 
@JsonIdentityReference(alwaysAsId = true) 
protected Location from; 

你的序列化JSON會看的這個代替:

{ 
    "from": { 
     "id": 3, 
     "description": "New-York" 
    } 
} 

這樣的:

{ 
    "from": 3 
} 

official documentation所述:

@JsonIdentityReference - 可以被用於參考的 定製細節對象進行「對象 同一性」被啓用可選註解(見JsonIdentityInfo

alwaysAsId = true用作標記,用於指示是否所有被引用的 值將被序列化爲ID(真);

注意,如果使用的「真」值,反序列化可能需要額外的上下文信息,並可能使用自定義ID 解析 - 默認處理方式可能是不夠的。

+0

這真的很有幫助,謝謝! – Jerry

+0

是@JsonIdentityInfo這裏必要的嗎? – kiedysktos

+0

@kiedysktos是的。 – VadymVL

1

只能忽略使用@JsonIgnore註釋您的JSON內容。 你想在你的JSON中隱藏的字段可以用@JsonIgnore來註釋。 你可以改變你的JSON這樣的:

{ 
    "id": 0, 
    "reservations": [ 
     {} 
    ], 
    "name": "string", 
    "dateOfDeparture": "string", 
    "distance": 0, 
    "price": 0, 
    "seats": 0, 
    "from": { 
     "id": 0 
    }, 
    "to": { 
     "id": 0 
    } 
} 

,但你可以不喜歡這樣的:

{ 
    "id": 0, 
    "reservations": [ 
     {} 
    ], 
    "name": "string", 
    "dateOfDeparture": "string", 
    "distance": 0, 
    "price": 0, 
    "seats": 0, 
    "from": 0, 
    "to": 1 
} 
+4

我認爲第二部分是不正確的,如其他答案所示。 – PhoneixS

+0

我同意@Amit khanduri – Johan