我将 Retrofit 库与 Gson 结合使用,并最初尝试过:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Dog.class, new Dog.Deserializer());
Gson dogGson = builder.create();
builder = new GsonBuilder();
builder.registerTypeAdapter(Cat.class, new Cat.Deserializer());
Gson catGson = builder.create();
builder = new GsonBuilder();
builder.registerTypeAdapter(Owl.class, new Owl.Deserializer());
Gson owlGson = builder.create();
Retrofit client = new Retrofit.Builder()
.baseUrl(buildType.apiEndpoint)
.addConverterFactory(new StringConverterFactory())
.addConverterFactory(GsonConverterFactory.create(dogGson))
.addConverterFactory(GsonConverterFactory.create(catGson))
.addConverterFactory(GsonConverterFactory.create(owlGson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
但是 Cat
和 Owl
的反序列化器不起作用,只有 Dog
的反序列化器被正确调用。经过一番修改后,我尝试了这个:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Dog.class, new Dog.Deserializer());
builder.registerTypeAdapter(Cat.class, new Cat.Deserializer());
builder.registerTypeAdapter(Owl.class, new Owl.Deserializer());
Gson deserializerGson = builder.create();
Retrofit client = new Retrofit.Builder()
.baseUrl(buildType.apiEndpoint)
.addConverterFactory(new StringConverterFactory())
.addConverterFactory(GsonConverterFactory.create(deserializerGson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
这有效,但让我困惑为什么第一种方法不起作用。我不能创建多个 GsonBuilder 吗?这是怎么回事?
最佳答案
您可以创建多个 GsonBuilder - 这部分代码的工作方式如您所期望的那样。在我看来,问题可能在于向您的 Retrofit Builder 添加多个相同类型的 ConverterFactory 。当您的 Retrofit 需要将某些 json 转换为对象时,它会查看其转换器列表,并挑选出第一个可以处理 Gson 的转换器。 (在本例中是带有 Dog 解串器的。)
关于java - 为什么我不能创建多个 GsonBuilder 并为每个 GsonBuilder 注册不同类型的适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863046/