gpt4 book ai didi

java - 修改 REST API 响应以仅包含查询参数中请求的字段

转载 作者:行者123 更新时间:2023-12-02 20:31:26 25 4
gpt4 key购买 nike

我想发送仅包含 GET API 请求字段的响应。减少响应的总大小。

例如,默认行为,何时请求特定字段:

GET /v1/users/

{
"data" :
[
{
"name" : "User1",
"phone" : "800-999-9999",
"city" : "XYZ1",
"country" : "PQR1"
},
{
"name" : "User2",
"phone" : "800-999-9999",
"city" : "XYZ2",
"country" : "PQR2"
}
]
}

用例,其中所需的字段作为查询参数传递

GET /v1/users/?fields=name,city

{
"data" :
[
{
"name" : "User1",
"city" : "XYZ1"
},
{
"name" : "User2",
"city" : "XYZ2"
}
]
}

遇到“https://github.com/monitorjbl/json-view”。但被团队击落。

如何使用 Spring Boot 实现此功能?使用java微服务的组织如何实现此功能?

最佳答案

方法一:将对象转为Map,去掉多余的key,将Map转为Json

@GetMapping("/v1/users")
@ResponseBody
public List<Map> getUsers(@RequestParam(required = false) Set<String> fields) {
List<User> users = ...;
ObjectMapper oMapper = new ObjectMapper();
return users.stream().map(u -> oMapper.convertValue(u, Map.class))
.peek(map -> {
if (fields != null) map.keySet().retainAll(fields)
})
.collect(Collectors.toList());
}

方法二:使用Gson

@GetMapping("/v1/users")
@ResponseBody
public String getUsers(@RequestParam(required = false) Set<String> fields) {
List<User> users = ...;
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(User.class)
&& fields != null
&& !fields.contains(f.getFieldName())
;
}

@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}).create();
return gson.toJson(users);
}

Came across "https://github.com/monitorjbl/json-view". But was shot down by the team.

顺便说一句,Jackson 有 @JsonView 注释支持,但它不允许根据需要动态包含/排除字段。您可以定义字段子集,然后返回这些子集

public class Views {
public static class Short {
}
}

public class User {
@JsonView(Views.Short.class)
public String city;

@JsonView(Views.Short.class)
public String name;

public String phone;

public String country;
}

@GetMapping("/v1/users")
@ResponseBody
public String getUsers(@RequestParam(required = false) boolean shortView) {
List<User> users = ...;
ObjectMapper mapper = new ObjectMapper();
if (shortView) mapper = mapper.writerWithView(Views.Short.class);
return mapper.writeValueAsString(users);
}

关于java - 修改 REST API 响应以仅包含查询参数中请求的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58785222/

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