2015-11-02 82 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