android - 使用改造和 Moshi 解析 api 响应不完全 "json"

标签 android json api retrofit2 moshi

我找到了我想尝试的 api,但响应不是“完整的 json”,所以当我得到响应时,我得到了解析器错误。

像往常一样,我正在使用改造,所以或多或少的重要部分是这样的:

val retrofit = Retrofit.Builder()
            .baseUrl(AwsomeAPIConstants.HOST)
            .addConverterFactory(MoshiConverterFactory.create())
            .build()

        awsomeApi = retrofit.create(AwsomeaApiService::class.java)

正如我所说,API 的所有响应都是这样的:<sentence> = {<json>}显然 MoshiConverter 无法解析它。

响应的一些例子:

info={'timestamp':1292608331,'error':0}

info={'status':1,'error':0}

search={'error':1}

有什么办法可以解析吗?

最佳答案

制作一个响应主体转换器,它采用响应主体的源,跳过前导字节和委托(delegate)。 下面是一个添加注释的示例,用于标记在其响应主体中具有此前缀的服务方法。

final class Foo {
  long timestamp;
  int error;
}

interface FooService {
  @EqualsJson @GET("/") Call<Foo> foo();
}

@Test public void foo() throws IOException {
  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse().setBody("info={'timestamp':1292608331,'error':0}"));
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(new EqualsJson.ResponseBodyConverterFactory())
      .addConverterFactory(MoshiConverterFactory.create().asLenient())
      .build();
  FooService fooService = retrofit.create(FooService.class);

  Call<Foo> call = fooService.foo();
  Response<Foo> response = call.execute();
  Foo body = response.body();
  assertThat(body.timestamp).isEqualTo(1292608331);
  assertThat(body.error).isEqualTo(0);
}

@Retention(RUNTIME)
public @interface EqualsJson {
  final class ResponseBodyConverterFactory extends Converter.Factory {
    @Nullable
    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(
        Type type, Annotation[] annotations, Retrofit retrofit) {
      for (int i = 0; i < annotations.length; i++) {
        Annotation annotation = annotations[i];
        if (annotation instanceof EqualsJson) {
          Annotation[] nextAnnotations = new Annotation[annotations.length - 1];
          System.arraycopy(
              annotations, 0, nextAnnotations, 0, i);
          System.arraycopy(
              annotations, i + 1, nextAnnotations, i, annotations.length - i - 1);
          return new ResponseBodyConverter(
              retrofit.nextResponseBodyConverter(this, type, nextAnnotations));
        }
      }
      return null;
    }

    static final class ResponseBodyConverter implements Converter<ResponseBody, Object> {
      static final ByteString JSON_PREFIX = ByteString.encodeUtf8("=");

      final Converter<ResponseBody, ?> delegate;

      ResponseBodyConverter(Converter<ResponseBody, Object> delegate) {
        this.delegate = delegate;
      }

      @Override
      public Object convert(ResponseBody value) throws IOException {
        BufferedSource source = value.source();
        source.skip(source.indexOf(JSON_PREFIX) + 1);
        return delegate.convert(
            ResponseBody.create(value.contentType(), value.contentLength(), source));
      }
    }
  }
}

关于android - 使用改造和 Moshi 解析 api 响应不完全 "json",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53600192/

相关文章:

java - Android - 如果未安装,如何获取应用程序图标?

java - Jackson Spring Controller 序列化

php - PHP : functions, 或类中 API 的最佳实践?

api - 如何从 Azure API 管理获取 API 使用数据?

java - 在 Keycloak 中创建新用户期间未分配客户端角色

android - Xamarin Android ExpandbleListView 添加子项

android - Okhttp 在不下载文件的情况下检查文件大小

android - 将 LinearView 和 ExpandableListView 放入 ScrollView 是否可能且有效

java - JSONArray 中的唯一 JSONObject

json - node.js 和 json 运行时错误