为什么我不能创建多个GsonBuilder并为每个适配器注册不同类型的适配器?

问题描述:

我用的是改造图书馆与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

你并不孤单,我在这里也经历过同样的情况! –

您可以创建多个GsonBuilders - 您的代码部分工作就像您期望的那样。在我看来,问题可能是在您的Retrofit Builder中添加了多个相同类型的ConverterFactory。当您的Retrofit需要将某个json转换为对象时,它会查看它的转换器列表,并挑选出第一个可以处理Gson的json。 (在这种情况下,与狗解串器一起使用)。

+0

啊,这很有道理 – Sree