我用的是改造圖書館與GSON一起,並嘗試這種最初:爲什麼我不能創建多個GsonBuilder併爲每個適配器註冊不同類型的適配器?
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
嗎?這裏發生了什麼?
你並不孤單,我在這裏也經歷過同樣的情況! –