在 spring boot 中检索特定字段

Hab*_*chi 7 java rest spring spring-boot spring-filter

我使用 Spring boot 开发了一个宁静的 API,我正在尝试找出实现部分响应结果的最佳方法。现在我的/user/{Id}端点返回如下内容:

{
    "firstname": "Jhon",
    "lastname": "Doe",
    "address": "156 Proton street",
    "username": "jhonDoe",
    "email": "jhon.doe@email.com",
    "company": "Fiction corp"
}
Run Code Online (Sandbox Code Playgroud)

我想要实现的是公开一个带有请求参数字段的端点,我可以在其中指定要检索的属性,因此端点将是类似的/users/{id}/fields=firstname,lastname,company,结果将是:

{
    "firstname": "Jhon",
    "lastname": "Doe",
    "company": "Fiction corp"
}
Run Code Online (Sandbox Code Playgroud)

我已经做了一些研究并找到了一篇关于Squiggle库的文章,但他们没有提到如何将其与 Spring Boot 集成,此外,如果有任何其他库不必只处理序列化但生成基于自定义查询的库在 Spring 数据(存储库)上仅检索指定的字段将是最受欢迎的。

有没有这样的解决方案?或者有人已经想出如何在他们现有的应用程序中配置 Squiggle?

qmt*_*mtq 6

经过更多的实验,我找到了在 Controller 中使用带有 spring boot 和 spring web 注释的 Squiggly 库的最简单方法。您应该做的唯一一件事是添加配置类,如下所示:

@Configuration
@ConditionalOnClass(ObjectMapper.class)
public class SquigglyAutoconfigure {

@Bean
public FilterRegistrationBean squigglyRequestFilter(ObjectMapper objectMapper) {
        Squiggly.init(objectMapper, new RequestSquigglyContextProvider());

        FilterRegistrationBean<SquigglyRequestFilter> filter = new FilterRegistrationBean<>();
        filter.setFilter(new SquigglyRequestFilter());
        filter.setOrder(1);
        return filter;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后当您将查询参数“字段”添加到控制器内的任何端点时:

@RequestParam(name = "fields", required = false) String fields
Run Code Online (Sandbox Code Playgroud)

您将获得过滤的回复。例如这种响应体:

{
  "id": "ISSUE-1",
  "issueSummary": "Dragons Need Fed",
  "issueDetails": "I need my dragons fed pronto.",
  "reporter": {
      "firstName": "Daenerys",
      "lastName": "Targaryen"
  }
}
Run Code Online (Sandbox Code Playgroud)

当您使用fields=id,reporter.firstName提出请求时您将获得:

{
  "id": "ISSUE-1",
  "reporter": {
      "firstName": "Daenerys"
  }
}
Run Code Online (Sandbox Code Playgroud)

更多嵌套对象、集合等示例:https : //github.com/bohnman/squiggly-java#reference-object