2016-10-04 95 views
1

我用的是改造圖書館與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(); 

CatOwl的解串器不工作,只有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嗎?這裏發生了什麼?

+0

你並不孤單,我在這裏也經歷過同樣的情況! –

回答

1

您可以創建多個GsonBuilders - 您的代碼部分工作就像您期望的那樣。在我看來,問題可能是在您的Retrofit Builder中添加了多個相同類型的ConverterFactory。當您的Retrofit需要將某個json轉換爲對象時,它會查看它的轉換器列表,並挑選出第一個可以處理Gson的json。 (在這種情況下,與狗解串器一起使用)。

+0

啊,這很有道理 – Sree

相關問題