我需要在retrofit2中使用jsonapi。我尝试使用moshi-jsonapi,但我无法使用moshi ConverterFactory。
TokenModel.java
$('.input-group.date').datepicker({
format: 'dd/mm/yyyy',
startDate: 'today'
});
TestService.java:
@JsonApi(type = "tokens")
public class TokenModel extends Resource {
@Json(name = "cell_phone")
public String cellPhone;
}
TestProvider.java:
public interface TestService {
@POST("token")
Call<TokenModel> newOtp(@Body TokenModel tokenModel);
}
如果我使用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
答案 0 :(得分:8)
从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();
这应该可以解决问题。