gpt4 book ai didi

java - 使用 Jackson 反序列化 JSON

转载 作者:行者123 更新时间:2023-11-30 06:21:44 26 4
gpt4 key购买 nike

出于某种原因,Jackson 2.3.0 无法解析 JSONP 响应。

com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'my_json_callback':

我已经让反序列化过程在没有回调的情况下工作。

我已经尝试使用包含 @JSONP 注释的 Jackson JAX-RS 包,但这似乎只在序列化时使用。

最佳答案

这是我使用 ReaderInterceptor 想出的解决方案的缩减空间版本。我将 Jersey 2.x 与 Jackson 结合使用,以与仅输出 JSONP 的 Web 服务进行交互。

public class CallbackStripInterceptor implements ReaderInterceptor {

private final static byte[] callbackBytes = "callback(".getBytes();

@Override
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {

int howMany = callbackBytes.length;

InputStream x = context.getInputStream();

if( !(x.available() >= howMany) ) {
return context.proceed();
}

x.mark( howMany );
byte[] preamble = new byte[ howMany ];
x.read( preamble );

// In case the first part of our entity doesn't have the callback String, reset the stream so downstream exploiters get the full entity.
if( !Arrays.equals( preamble, callbackBytes ) ) {
x.reset();
}

return context.proceed();
}

像这样使用:

Client c = ClientBuilder.newBuilder()
.register( new CallbackStripInterceptor() )
.build();

使用此客户端,所有带有实体的响应都将通过此拦截器(Jersey 不会对没有实体主体的响应运行拦截器)。

关于java - 使用 Jackson 反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20069088/

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