简体   繁体   English

如何在Jackson xml解析器中将octet-stream解析为json?

[英]How to parse octet-stream as json in Jackson xml parser?

I sometimes receive a webservice response where the content-type=application/octet-stream is set, anyways it's in fact application/xml . 我有时会收到一个webservice响应,其中设置了content-type=application/octet-stream ,无论如何它实际上是application/xml

As I'm not in control of the webservice, I'd still like to tell jackson (that I'm using with spring-boot ) to parse those responses as xml. 由于我无法控制web服务,我仍然想告诉jackson(我正在使用spring-boot )将这些响应解析为xml。 But how? 但是怎么样?

I first tried to allow octet-stream at all for the jackson mapper, which works so far: 我首先尝试为jackson mapper提供octet-stream,这对于目前为止工作:

@Bean
public RestTemplateCustomizer customizeJackson2MessageConverter() {
    return restTemplate -> {
        for (var converter : restTemplate.getMessageConverters()) {
            if (converter instanceof MappingJackson2HttpMessageConverter) { 
                jackson.getSupportedMediaTypes().add((MediaType.APPLICATION_OCTET_STREAM);
            }
        }
    };
}

BUT: when it then comes to the parsing, how can I tell jackson to ignore/rewrite the content-type, and still parse it as normal json? 但是:当它进入解析时,如何告诉jackson忽略/重写内容类型,并仍然将其解析为普通的json?

Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: (ByteArrayInputStream); line: 1, column: 2]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:245) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:102) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 113 more

I did as advised by @chrylis: 我按照@chrylis的建议做了:

public class ContentTypeInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse http = execution.execute(request, body);

        HttpHeaders headers = http.getHeaders();
        if (headers.getContentType() == MediaType.APPLICATION_OCTET_STREAM) {
            headers.setContentType(MediaType.APPLICATION_XML);
        }

        return http;
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM