gpt4 book ai didi

java - Spring Rest 存储库 -> 如何动态省略响应中的字段

转载 作者:行者123 更新时间:2023-12-02 11:01:37 24 4
gpt4 key购买 nike

我有一个休息服务,客户希望能够指定端点中返回哪些字段。

我正在使用 PagingAndSortingRepository 从模型生成端点。

例如:http://localhost:8080/users会返回

{
name: "John",
age: 23,
gender: "Male",
salary: 25000.0
}

他们希望返回http://localhost:8080/users?fields=name,age,gender..

{
name: "John",
age: 23,
gender: "Male"
}

我可以进行预测,但这需要是动态的,因为我们有很多字段。

这可能吗?

最佳答案

我认为这种方式没有多大值(value),但如果你真的想实现这一点,那么我在GitHub上创建了示例Spring boot应用程序.

首先,有一个模型来保存数据并添加 @JsonInclude(JsonInclude.Include.NON_NULL) 以忽略空字段,如下所示:

@JsonInclude(JsonInclude.Include.NON_NULL)
@Setter
@Getter
@AllArgsConstructor
public class User {
private String name;
private Integer age;
private Float salary;
private String gender;
}

你的 Controller 方法将是这样的:

    @GetMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public User getString(@RequestParam List<String> fields) {
User user = new User("Yogen", 26, 3000.00f, "male");
ReflectionUtils.doWithFields(User.class, field -> {
if (!fields.contains(field.getName())) {
field.setAccessible(true);
field.set(user, null);
}
},
field -> {
final int modifiers = field.getModifiers();
// no static fields please
return !Modifier.isStatic(modifiers);
});
return user;
}

这里我使用Spring的ReflectionUtils来过滤字段。

因此,您的请求 http://localhost:8089/?fields=name,salary 将返回:

{
"name": "Yogen",
"salary": 3000
}

关于java - Spring Rest 存储库 -> 如何动态省略响应中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51294726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com