简体   繁体   English

当序列化有条件地跳过符合 Jackson 自定义标准的对象时修改 HTTP 代码(Spring 启动)

[英]Modify HTTP code when Serialize skipping objects conditionally that meet a Custom Criteria with Jackson (Spring boot)

So i was able to Serialize skipping objects conditionally that meet a Custom Criteria with Jackson following provided link.因此,我能够按照提供的链接对满足自定义标准的 Jackson 有条件地跳过对象进行序列化。 link: https://www.baeldung.com/jackson-serialize-field-custom-criteria链接: https : //www.baeldung.com/jackson-serialize-field-custom-criteria

NOTE: i was able to do it without the filter.注意:我可以在没有过滤器的情况下做到这一点。

So what i'm doing basically, checking for an attribute, and if it wasn't set, i skip returning the whole object.所以我基本上在做什么,检查一个属性,如果它没有设置,我跳过返回整个对象。 so what i'm getting (basing on the tutorial example):所以我得到了什么(基于教程示例):

HTTP: 200
PATH: /users
RESPONSE:
[
    {
        "name":"john"
    },
    {
        "name":"adam",
        "address":{
            "city":"ny",
            "country":"usa"
        }
    }
]

But if we came to a case to return a single user, who is hidden, we will face this:但是如果我们遇到一个案例返回一个隐藏的单个用户,我们将面临这样的问题:

HTTP: 200
PATH: /users/tom
RESPONSE: /**empty response**/

In this particular case, i want to return a HTTP response with 404 error code, not 200 like the jackson is behaving.在这种特殊情况下,我想返回一个带有 404 错误代码的 HTTP 响应,而不是像 jackson 那样的 200。 when debugging, Jackson is serializing after the controller, so i couldn't intercept it.调试时,Jackson 在控制器之后序列化,所以我无法拦截它。

I was thinking of implementing interceptors, which could intercept the jackson response writer and then if empty, return a 404 error code.我正在考虑实现拦截器,它可以拦截杰克逊响应编写器,然后如果为空,则返回 404 错误代码。

...I'm out of ideas, and leak of experience. ...我没有想法,经验泄漏。 :/ :/
does anyone knows how to do this?有谁知道如何做到这一点?

EDIT::20200323编辑::20200323

following @Tomoki_Sato answer, i have found a solution.按照@Tomoki_Sato 的回答,我找到了解决方案。 After trying his answer, it didn't work first.在尝试了他的回答后,它首先不起作用。 After investigating, the issue was with type mismatch.经过调查,问题出在类型不匹配上。
In my controller, i always return ResponseEntity<?> which doesn't implement the Hideable class.在我的控制器中,我总是返回ResponseEntity<?> ,它没有实现Hideable类。

So my solution was like that, supporting ResponseEntity<<? implements Hideable>>所以我的解决方案就是这样,支持ResponseEntity<<? implements Hideable>> ResponseEntity<<? implements Hideable>> && <? implements Hideable> ResponseEntity<<? implements Hideable>> && <? implements Hideable> <? implements Hideable> responses: <? implements Hideable>响应:

@RestControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Hideable> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //if returnType is  <? implements hideable>
        if (Hideable.class.isAssignableFrom(returnType.getParameterType()) && MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType)) {
            return true;
        }

        //if returnType is  ResponseEntity<<? implements hideable>>
        List<Type> actualTypeArguments = Lists.newArrayList(((ParameterizedType) returnType.getGenericParameterType()).getActualTypeArguments());
        if (actualTypeArguments.isEmpty()) {
            return false;
        }

        try {
            Class<?> responseClass = Class.forName(actualTypeArguments.get(0).getTypeName());
            return Hideable.class.isAssignableFrom(responseClass) && MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Hideable beforeBodyWrite(
        Hideable hideable, MethodParameter returnType, MediaType selectedContentType,
        Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
        ServerHttpResponse response
    ) {

        if (hideable == null || hideable.isRemoved()) {
            response.setStatusCode(HttpStatus.NOT_FOUND);
            return null;
        }
        return hideable;
    }
}

Talking about efficiency, i didn't tested it out, ad i believe we have to test it over many types like ResponseEntity<List<? implements Hideable>>谈到效率,我没有测试过,我相信我们必须在许多类型上测试它,比如ResponseEntity<List<? implements Hideable>> ResponseEntity<List<? implements Hideable>> , ResponseEntity<Set<? implements Hideable>> ResponseEntity<List<? implements Hideable>> , ResponseEntity<Set<? implements Hideable>> ResponseEntity<Set<? implements Hideable>> .... ResponseEntity<Set<? implements Hideable>> ....

In Theory, i believe that @RestControllerAdvice don't interfere here, and the JSON serializer is taking the lead converting the response... i don't know.在理论上,我相信@RestControllerAdvice不会在这里干扰,并且 JSON 序列化器正在率先转换响应......我不知道。

I hope this helps someone else :)我希望这对其他人有帮助:)

You can customize the response before Jackson writes it by implementing ResponseBodyAdvice .您可以通过实现ResponseBodyAdvice在 Jackson 编写响应之前自定义ResponseBodyAdvice
If you want to set the 404 HTTP status code when a user is null or hidden , your ResponseBodyAdvice implementation will be something like this:如果您想在user为 null 或hidden时设置404 HTTP 状态代码,您的ResponseBodyAdvice实现将是这样的:

@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Hidable> {

    /**
     * Supports `? extends Hidable`, `ResponseEntity<? extends Hidable>` and
     * `HttpEntity<? extends Hidable>` handled by
     * `MappingJackson2HttpMessageConverter`
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        if (!MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType)) {
            return false;
        }

        Class<?> parameterType = returnType.getParameterType();

        // if returnType is <? extends Hidable>
        if (Hidable.class.isAssignableFrom(parameterType)) {
            return true;
        }

        // if returnType is ResponseEntity<? extends Hidable> or HttpEntity<? extends
        // Hidable>
        if (HttpEntity.class.isAssignableFrom(parameterType)) {

            Type[] actualTypeArguments = ((ParameterizedType) returnType.getGenericParameterType())
                    .getActualTypeArguments();
            if (actualTypeArguments == null || actualTypeArguments.length != 1) {
                return false;
            }
            try {
                return Hidable.class.isAssignableFrom(Class.forName(actualTypeArguments[0].getTypeName()));
            } catch (ClassNotFoundException e) {
                // e.g. returnType is ResponseEntity<List<Hideable>>
                e.printStackTrace();
            }

        }

        return false;
    }

    @Override
    public Hidable beforeBodyWrite(Hidable hidable, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {

        if (hidable == null || hidable.isHidden()) {
            response.setStatusCode(HttpStatus.NOT_FOUND);
            return null;
        }
        return hidable;
    }
}

EDIT::20200324编辑::20200324

I improved my answer based on the code snippet in EDIT::20200323 above so that the ResponseBodyAdvice can support not only Hidable but also ResponseEntity and HttpEntity .我根据上面EDIT::20200323 中的代码片段改进了我的答案,以便ResponseBodyAdvice不仅可以支持Hidable还可以支持ResponseEntityHttpEntity
I'd like to suggest that you check whether HttpEntity (the super class of ResponseEntity ) is assignable from parameterType so that you can prevent your ResponseBodyAdvice from supporting unexpected parameter types like List<Hidable> .我想建议您检查HttpEntityResponseEntity的超类)是否可以从parameterType分配,以便您可以防止您的ResponseBodyAdvice支持意外的参数类型,如List<Hidable> If the ResponseBodyAdvice supports List<Hidable> , ClassCastException occurs at beforeBodyWrite .如果ResponseBodyAdvice支持List<Hidable>ClassCastException发生在beforeBodyWrite

See Also也可以看看
Spring Framework Documentation - Web on Servlet Stack - 1.1.6. Spring 框架文档 - Web on Servlet Stack - 1.1.6。 Interception 拦截
Java doc of ResponseBodyAdvice ResponseBodyAdvice 的 Java 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何序列化符合杰克逊自定义标准的列表 - How to serialize List that meet Custom Criteria with Jackson Spring Boot-JSON使用自定义对象数组序列化自定义对象 - Spring Boot - JSON Serialize Custom Object with Array of Custom Objects Spring 引导 Jackson 不序列化长时间戳 - Spring Boot Jackson does not serialize timestamps in Long 使用jackson序列化时有条件地跳过对象 - Skip objects conditionally when serializing with jackson Spring引导2.04 Jackson无法将LocalDateTime序列化为String - Spring boot 2.04 Jackson cannot serialize LocalDateTime to String 如何使用 Spring 和 Jackson 引导在没有纳秒的情况下序列化 Instant? - How to serialize an Instant without nanoseconds using Spring Boot with Jackson? 杰克逊自定义解串器在春季启动中无法正常工作 - Jackson Custom Deserializer Not Working In Spring Boot 在弹簧引导端点上使用自定义jackson映射器 - Use custom jackson mapper on spring boot endpoints 在 Java Spring Boot 中创建并返回自定义 Http 响应代码 - Create and Return a custom Http response code in Java Spring Boot 从 spring 引导自定义验证器返回不同的 HTTP 状态代码 - Return different HTTP status code from spring boot custom validators
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM