Spring Data Rest:从超媒体 Rest JPA 实体的响应中删除 _links 属性

问题描述 投票:0回答:2

我想自定义超媒体 Rest JPA 实体的响应,并希望删除所有 _links 属性和自链接属性。 我的客户端应用程序不是那么大,它知道要调用哪些确切的 REST API。因此,我觉得 HTTP 数据包中传输的这些额外字节始终是我的应用程序的开销。

那么我怎样才能从响应中删除这个链接属性呢?

现在 REST API 响应是:

{
  "_embedded" : {
    "questionsTypes" : [ {
      "queTypeID" : 2,
      "queDescription" : "Single choice rating selection",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/question_web/rest/QuestionsType/2"
        },
        "questionsType" : {
          "href" : "http://localhost:8080/question_web/rest/QuestionsType/2{?projection}",
          "templated" : true
        }
      }
    },{
      "queTypeID" : 5,
      "queDescription" : "Subjective questions",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/question_web/rest/QuestionsType/5"
        },
        "questionsType" : {
          "href" : "http://localhost:8080/question_web/rest/QuestionsType/5{?projection}",
          "templated" : true
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/question_web/rest/QuestionsType"
    },
    "profile" : {
      "href" : "http://localhost:8080/question_web/rest/profile/QuestionsType"
    },
    "search" : {
      "href" : "http://localhost:8080/question_web/rest/QuestionsType/search"
    }
  }
}

我期望的最终答复是这样的:

{
  "_embedded" : {
    "questionsTypes" : [ {
      "queTypeID" : 2,
      "queDescription" : "Single choice rating selection",
    },{
      "queTypeID" : 5,
      "queDescription" : "Subjective questions",
    } ]
  }
}
spring spring-data-rest spring-hateoas
2个回答
3
投票
@Component
public class MyEntityProcessor implements RepresentationModelProcessor<EntityModel<MyEntity>> {

    @Override
    public EntityModel<MyEntity> process(EntityModel<MyEntity> model) {
        return EntityModel.of(model.getContent());
    }

}

0
投票

从所有对象中删除所有 _links:

但是这个方法会覆盖任何其他处理器

@Component
public class ObjectRepresentationModelProcessor implements RepresentationModelProcessor<EntityModel<Object>> {

    @NonNull
    @Override
    public EntityModel<Object> process(EntityModel<Object> model) {
        return EntityModel.of(model.getContent());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.