java - 我如何在 Retrofit2 中使用 jsonapi?

标签 java android retrofit json-api moshi

我需要使用jsonapi在改造中2。我尝试使用 moshi-jsonapi但我不能使用 moshi ConverterFactory。

token 模型.java

@JsonApi(type = "tokens")
public class TokenModel extends Resource {
    @Json(name = "cell_phone")
    public String cellPhone;
}

测试服务.java:

public interface TestService {
    @POST("token")
    Call<TokenModel> newOtp(@Body TokenModel tokenModel);
}

测试提供者.java:

public class TestProvider {
    private TestService testService;

    public TestProvider() {
        OkHttpClient httpClient = new OkHttpClient();
        Retrofit refRetrofit = new Retrofit.Builder()
                .baseUrl(ClientConfigs.BASE_URL)
                .client(httpClient)
                .addConverterFactory(MoshiConverterFactory.create())
//                .addConverterFactory(????????????????????????????)
                .build();
        testService = refRetrofit.create(TestService.class);
    }

    publicTestService getTestService() {
        return testService;
    }
}

如果我使用 MoshiConverterFactory 会出错 Unable to create converter for class com.xxx.xxx.model.TokenModel!

使用改造:

TsetProvider testProvider = new TestProvider();
TestService testService = testProvider.getTestService();

TokenModel tokenModel = new TokenModel();
tokenModel.cellPhone = "121212129999";

Call<TokenModel> call = testService.newOtp(tokenModel);
call.enqueue(new Callback<TokenModel>() {
    @Override
    public void onResponse(Call<TokenModel> call, Response<TokenModel> response) {
    }

    @Override
    public void onFailure(Call<TokenModel> call, Throwable t) {
    }
});

最佳答案

来自 moshi-jsonapi将库工厂添加到 moshi 实例所需的文档:

// First create the factory
JsonAdapter.Factory jsonApiAdapterFactory = ResourceAdapterFactory.builder()
  .add(TokenModel.class)
  .build();

// Create a custom moshi instacne
Moshi moshi = new Moshi.Builder()
  .add(jsonApiAdapterFactory)
  .build();

// Add the custom moshi instance to Retrofits Converter Factory
Retrofit refRetrofit = new Retrofit.Builder()
  .baseUrl(ClientConfigs.BASE_URL)
  .client(httpClient)
  .addConverterFactory(MoshiConverterFactory.create(moshi))
  .build();

这应该可以解决问题。

关于java - 我如何在 Retrofit2 中使用 jsonapi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40608078/

相关文章:

java - 在 AnyLogic 的汇编器 block 中配置 "New Agent"

java - 使用 Twitter 搜索 API 时出现 400 错误代码

java - 改造-IllegalArgumentException : unexpected url

java - 循环遍历字符串来检查值。 (Java计算器)

java - 从 NetBeans 中的单独类关闭 JFrame(但不是整个程序)的 Dispose 方法不起作用。为什么?

java - 由于 Task attempt failed to report status 600 秒,reduce 失败。杀戮!解决方案?

java - 我可以以某种方式增加 USB 端点的大小吗?

android - Android中的样式底线

android - 带有由 LoaderManager 管理的自定义适配器的 AlphabetIndexer

retrofit - 是否可以同步运行可观察的改造?