gpt4 book ai didi

android - 定制改造转换器

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:36 26 4
gpt4 key购买 nike

我正在使用 Retrofit 作为 REST 客户端并得到以下响应:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{"Response":{"Status":"success","Response........... </string>

如何使 Retrofit 开始解析 xml 标记后的对象(如果可能),如果不能,是否有其他解决方案?

最佳答案

这很简单。据我所知,Retrofit 不提供转换器链,但您仍然可以包装多个转换器:

final class XmlWrappedConverterFactory
extends Converter.Factory {

// This is the converter factory the deserialization will be delegated to
private final Converter.Factory backingConverterFactory;

private XmlWrappedConverterFactory(final Converter.Factory backingConverterFactory) {
this.backingConverterFactory = backingConverterFactory;
}

static Converter.Factory create(final Converter.Factory backingConverterFactory) {
return new XmlWrappedConverterFactory(backingConverterFactory);
}

@Override
public Converter<ResponseBody, ?> responseBodyConverter(final Type type, final Annotation[] annotations, final Retrofit retrofit) {
final Converter<ResponseBody, ?> responseBodyConverter = backingConverterFactory.responseBodyConverter(type, annotations, retrofit);
return new XmlWrappedResponseBodyConverter(responseBodyConverter);
}

private static final class XmlWrappedResponseBodyConverter
implements Converter<ResponseBody, Object> {

private final Converter<ResponseBody, ?> responseBodyConverter;

private XmlWrappedResponseBodyConverter(final Converter<ResponseBody, ?> responseBodyConverter) {
this.responseBodyConverter = responseBodyConverter;
}

@Override
public Object convert(final ResponseBody responseBody)
throws IOException {
// Note the response is not converted to string in order to save memory and work in streaming fashion
// So just fast-forward until '>' is found -- let's pretend it's an XML pretty much then
fastForward(responseBody.charStream(), '>');
// GsonConverterFactory uses charStream() as well, at this step the stream will be "fast-forwarded"
return responseBodyConverter.convert(responseBody);
// However, the GsonConverterFactory closes the charStream() so wer're unable to read it until the end -- not that bad in fact
}

private static void fastForward(final Reader reader, final char ch)
throws IOException {
// Just read until the given character is found or EOF
int read;
while ( (read = reader.read()) != ch && read != -1 ) {
}
}

}

}

然后构建一个 Retrofit 实例很简单:

final Retrofit retrofit = new Builder()
...
.addConverterFactory(XmlWrappedConverterFactory.create(GsonConverterFactory.create()))
.build();

关于android - 定制改造转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42980677/

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