【问题标题】:Quarkus Rest client JSON serialization: equivalent of @JsonIgnore to ignore some field in serializationQuarkus Rest 客户端 JSON 序列化:相当于 @JsonIgnore 忽略序列化中的某些字段
【发布时间】:2022-11-09 00:22:52
【问题描述】:
如何忽略 Quarkus Rest Client 请求正文中的字段?我在依赖关系树中看到,这是列出的:
io.quarkus:quarkus-resteasy-reactive-jsonb:jar:2.7.5.Final:compile
并且使用来自com.fasterxml.jackson.annotation 的@JsonIgnore 或JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 不起作用。
我想这是因为MessageBodyWriter 使用的是 Jsonb 提供程序,而不是 Jackson。
【问题讨论】:
标签:
quarkus
quarkus-rest-client
quarkus-reactive
【解决方案1】:
在这里查看:https://download.eclipse.org/microprofile/microprofile-rest-client-2.0/microprofile-rest-client-spec-2.0.html#_json_p_and_json_b_providers
基本上,您需要注册一个提供程序来为您的休息客户端配置东西(但我认为如果您有很多字段要忽略,这很糟糕)。
我的暗示:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;
import javax.json.bind.config.PropertyVisibilityStrategy;
import javax.ws.rs.ext.ContextResolver;
public class EventJsonbCustomizer implements ContextResolver<Jsonb> {
@Override
public Jsonb getContext(Class<?> type) {
JsonbConfig jsonbConfig = new JsonbConfig()
.withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() {
@Override
public boolean isVisible(Field field) {
return !field.getDeclaringClass().equals(Event.class) ||
!field.getName().equals("package"); // if is this class and this field, return false; else true
}
@Override
public boolean isVisible(Method method) {
return false; // always false
}
});
return JsonbBuilder.newBuilder().withConfig(jsonbConfig).build();
}
}
其余的客户:
@ApplicationScoped // needed for @QuarkusTest injection
@Path("")
@RegisterProvider(EventJsonbCustomizer.class)
public interface EventSenderRestAPI extends AutoCloseable {
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response create(@HeaderParam(AUTHORIZATION) String authorization, Event event);
...
奇怪的,奇怪的做事方式。但最后它起作用了。