如何将Gson的Retrofit响应反序列化为不同的List类型?

时间:2018-05-09 22:03:53

标签: kotlin gson retrofit2

我在构建我的Retrofit实例时注册了一个TypeAdapter,该实例委托所有期望List响应的API调用:

val retrofit = Retrofit.Builder()
                .client(client)
                .baseUrl("$baseURL/")
                .addConverterFactory(
                        GsonConverterFactory.create(
                                GsonBuilder().registerTypeAdapter(List::class.java, MatchesDeserializer()) //Delegates all calls expecting return of type List.
                                        .registerTypeAdapter(Array<String>::class.java, PhotoDeserializer()) //This works, because it's a different type.
                                        .registerTypeAdapter(Triple::class.java, ChatMessagesDeserializer())
                                        .create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
                .build()

现在,我所做的唯一调用需要一个相同类型的List(User,需要自定义反序列化器),但我希望能够调用返回不同类型的列表(比如Item,它会自动反序列化) )。问题是我不能指定MatchesDeserializer应该用于哪种List类型,因为类文字不能包含类型信息。我们可以为没有问题的数组响应指定类型。

GsonBuilder().registerTypeAdapter(List<String>::class.java, MatchesDeserializer()) //This doesn't compile.

我可以更改所有希望List返回JsonObject的调用,并使用我的反序列化器手动解析它,或者实现TypeAdapterFactory以手动反序列化用户类型。

有更优雅的方法吗?

0 个答案:

没有答案
相关问题