我使用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,但是不知道如何在我的情况下使用它(如果有可能的话)

最佳答案

我偶然发现了这个问题,正在寻找解决方案。摆弄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();
}

这里重要的一点是,您的Projection需要引用UserExcerpt而不是User。这样,从GET /accounts/projection=accountUsersProjection返回的结果将如下所示:
{
  "_embedded" : {
    "accounts" : [ {
      "name" : "ProjA",
      "users" : [ {
        "name" : "Customer Admin",
        "email" : "[email protected]",
        "_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
  }
}

10-06 14:42