簡體   English   中英

在Spring Boot中檢索特定字段

[英]Retrieve specific fields in spring boot

我使用Spring Boot開發了一個寧靜的API,並且我試圖找到實現部分響應結果的最佳方法。 現在,我的/user/{Id}端點返回如下內容:

{
    "firstname": "Jhon",
    "lastname": "Doe",
    "address": "156 Proton street",
    "username": "jhonDoe",
    "email": "jhon.doe@email.com",
    "company": "Fiction corp"
}

我要實現的是公開一個帶有請求參數字段的端點,我可以在其中指定要檢索的屬性,因此端點將像/users/{id}/fields=firstname,lastname,company和結果將是:

{
    "firstname": "Jhon",
    "lastname": "Doe",
    "company": "Fiction corp"
}

我已經進行了一些研究,找到了一篇有關Squiggle庫的文章,但是他們沒有提及如何將其與Spring boot集成在一起。此外,如果還有其他庫不必僅處理序列化,而是可以生成基於Query的自定義查詢在Spring數據(存儲庫)上僅用於檢索指定字段的方法將受到歡迎。

有沒有這樣的解決方案? 還是有人已經想出了如何在現有應用程序中配置Squiggle?

經過更多的實驗,我發現在Controller中將Squiggly庫與spring boot和spring web批注一起使用的最簡單方法。 您應該做的唯一一件事是添加配置類,如下所示:

@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;
    }
}

然后,當您將查詢參數“字段”添加到控制器內的任何端點時:

@RequestParam(name = "fields", required = false) String fields

您將過濾出響應。 例如,使用這種響應主體:

{
  "id": "ISSUE-1",
  "issueSummary": "Dragons Need Fed",
  "issueDetails": "I need my dragons fed pronto.",
  "reporter": {
      "firstName": "Daenerys",
      "lastName": "Targaryen"
  }
}

當您使用fields = id,reporter.firstName發出請求時您將獲得:

{
  "id": "ISSUE-1",
  "reporter": {
      "firstName": "Daenerys"
  }
}

有關嵌套對象,集合和其他對象的更多示例: https : //github.com/bohnman/squiggly-java#reference-object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM