网站备案下来以后怎么做网页,如何设计网站,wordpress the_,搜索引擎大全排名项目用已经使用了 Retrofit#xff0c;定义了接口方法#xff0c;返回了 JSON 转换后的实体对象#xff0c;炒鸡方便。但是总有意料之外的时候#xff0c;比如我不需要返回实体对象#xff0c;我要返回纯纯的 JSON 字符串#xff0c;怎么办呢#xff1f;
先看源码
通过…
项目用已经使用了 Retrofit定义了接口方法返回了 JSON 转换后的实体对象炒鸡方便。但是总有意料之外的时候比如我不需要返回实体对象我要返回纯纯的 JSON 字符串怎么办呢
先看源码
通过一系列的源码分析最后定位到 OkHttpCall 中的 parseResponse() 方法 下面代码中的 parseResponse 方法是纯复制过来的没改过可以看出当接口返回正确的数据之后无论如何都会调用 T body responseConverter.convert(catchingBody)把 JSON 字符串转换成了一个 T 对象我们没有办法通过配置什么东西来实现我们要返回纯 JSON 字符串的需求所以要想其他办法。两个办法1、让它转我们再转回来2、我们自己定义怎么转。
final class OkHttpCallT implements CallT {ResponseT parseResponse(okhttp3.Response rawResponse) throws IOException {ResponseBody rawBody rawResponse.body();// Remove the bodys source (the only stateful object) so we can pass the response along.rawResponse rawResponse.newBuilder().body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();int code rawResponse.code();if (code 200 || code 300) {try {// Buffer the entire body to avoid future I/O.ResponseBody bufferedBody Utils.buffer(rawBody);return Response.error(bufferedBody, rawResponse);} finally {rawBody.close();}}if (code 204 || code 205) {rawBody.close();return Response.success(null, rawResponse);}ExceptionCatchingResponseBody catchingBody new ExceptionCatchingResponseBody(rawBody);try {T body responseConverter.convert(catchingBody);return Response.success(body, rawResponse);} catch (RuntimeException e) {// If the underlying source threw an exception, propagate that rather than indicating it was// a runtime exception.catchingBody.throwIfCaught();throw e;}}
}方法一返回 JSONObject 后再转 JSON 字符串
这个很简单我们把返回实体类改成 JSONObject然后 Converter 会帮忙我们转成 JSONObject然后我们再转成字符串即可。缺点就是转了两轮。
// 接口定义
POST(xxx)
fun fetch(Body param: RequestBody): CallJSONObject// 使用
val response api.fetch(param).execute()
val json response.body()?.toJSONString() ?: 方法二自定义 Converter
模仿 FastJsonResponseBodyConverter 自定义一个 Converter直接返回字符串不转实体对象即可收工。
// 自定义Converter
// 挖坑理论上可以定义一个注解然后判断 annotations 中是否包含此注解
// 如果包含则返回自定义Converter否则返回原来的Converter。
.addConverterFactory(object : Converter.Factory() {override fun responseBodyConverter(type: Type,annotations: Arrayout Annotation,retrofit: Retrofit): ConverterResponseBody, String {return ConverterResponseBody, String { responseBody -responseBody.use { it.string() }}}
})// 接口定义
POST(xxx)
fun fetch(Body param: RequestBody): CallString// 使用
val response api.fetch(param).execute()
val json response.body() ?: