我使用Spring Data REST的projections功能,以便在JSON中包含一些嵌套类型的对象:
{
"id": 1,
"name": "TEST",
"user": {
"id": 1,
"name": "user1"
},
_links: {
self: {
href: "http://localhost:8082/accounts/1{?projection}",
templated: true
},
user: {
href: "http://localhost:8082/accounts/1/users"
},
}
}
如何在嵌套对象中生成链接?我想要以下JSON表示:
{
"id": 1,
"name": "TEST",
"user": {
"id": 1,
"name": "user1",
_links: {
self: {
href: "http://localhost:8082/users/1",
templated: true
},
}
},
_links: {
self: {
href: "http://localhost:8082/accounts/1{?projection}",
templated: true
},
user: {
href: "http://localhost:8082/accounts/1/users"
},
}
}
P.S。我看到了this question,但我不知道如何在我的情况下使用它(如果它可能的话)
答案 0 :(得分:3)
我偶然发现了这个问题,寻找解决方案。经过一些摆弄Spring Data REST docs section on Excerpts之后,我发现了如何实现这一目标。
我认为Account
是您的根对象,并且您希望它具有Users
的嵌套集合,其中每个用户又有_links
。
1:为Users对象添加Excerpt
(这是一种方便的技术,可以隐藏列表集合中不重要的细节)
@Projection(name = "userExcerpt", types = { User.class })
public interface UserExcerpt {
String getName();
String getEmail();
...
}
2:将Excerpt
与您的UserRepository
@RepositoryRestResource(excerptProjection = UserExcerpt.class)
public abstract interface UserRepository extends JpaRepository<User, Long> ...
3:为Projection
添加Account
:
@Projection(types = {Account.class})
public interface AccountUsersProjection {
String getName();
...
Set<UserExcerpt> getUsers();
}
这里重要的一点是,您的投影需要引用UserExcerpt
而不是User
。这样,GET /accounts/projection=accountUsersProjection
返回的结果将如下所示:
{
"_embedded" : {
"accounts" : [ {
"name" : "ProjA",
"users" : [ {
"name" : "Customer Admin",
"email" : "customer@meshcloud.io",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/2{?projection}",
"templated" : true
}, ...
}
} ],
"_links" : {
"self" : {
"href" : "http://localhost:8080/accounts/1"
},
...
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/accounts"
},
...
},
"page" : {
"size" : 50,
"totalElements" : 2,
"totalPages" : 1,
"number" : 0
}
}