【问题标题】:Reduce the JSON Response in Spring Boot减少 Spring Boot 中的 JSON 响应
【发布时间】:2021-06-15 13:23:21
【问题描述】:

我有这种类型的JSON 也应用过滤器

"apps": [
            {
                "id": 78,
                "createdAt": "05-26-2021 08:53:00",
                "title": "Testing App 51",
                "updatedAt": "05-26-2021 08:53:32",
                "organizationId": 1,
    }]

但我想在我想要的不同类型的 JSON 响应中应用 shortmediumlong。 例如:在 short 中,我只需要 JSON 中的 idtitle 。 我使用generic specification 传递实体对象并将整个实体作为 JSON 响应返回。

【问题讨论】:

  • 这个问题我很不清楚。但这听起来像是 Json 视图可以解决的问题? baeldung.com/jackson-json-view-annotation
  • @Gimby 有什么不清楚的地方请详细说明?
  • 没有代码,只是一个模糊的高级描述。我也不知道什么是“通用规范”。
  • @Gimby 我面临的问题是我的实体的 JSON 响应太大,例如我有大约 25 列,但我在 JSON 响应中只需要一些列,所以我想创建三个查询,即我想在其中得到四列的短查询,而不是在中我正在寻找 12 列和在“长”中我正在寻找 18列,但此刻我被卡住了。如果您有任何解决方案或任何链接,我可以从中获得一些知识,这将非常有帮助。谢谢!!
  • 我在第一条评论中提供的链接怎么样?

标签: java json spring spring-boot


【解决方案1】:

我认为你可以使用SimpleBeanPropertyFilter + FilterProvider + MappingJacksonValue 的组合。它可以帮助您在将对象序列化为 JSON 时动态地忽略字段。

// set the filter ID "appFilter"
@JsonFilter("appFilter")
public class App {
  private Integer id;
  private String title;
  private Integer organizationId;
  ... getter / setter ...
}

// In the controller,
@GetMapping("/app/{id}")
public MappingJacksonValue getApp(@PathVariable("id") Integer id) {
  // make a json except the key "organizationId:
  SimpleBeanPropertyFilter sbpf = SimpleBeanPropertyFilter.serializeAllExcept("organizationId");
  // make a filter provider
  FilterProvider fp = new SimpleFilterProvider().addFilter("appFilter", sbpf);
  // fetch an app data
  App app = appService.getApp(id);
  // apply the filter provider for the instance of App.
  MappingJacksonValue mjv = new MappingJacksonValue(app);
  mappingJacksonValue.setFilters(filterProvider);
  return mjv;
}

希望你有一个提示。我找到了那个代码here

编码愉快!

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 2018-07-13
    • 2020-10-05
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多