【问题标题】:Unable to create converter for class..., Retrofit2, Realm4 and GSON无法为类...、Retrofit2、Realm4 和 GSON 创建转换器
【发布时间】:2017-10-31 23:03:12
【问题描述】:

这不是一个问题。它解释了另一种获取此异常的方法。
所以我使用 Retrofit 2 并且已经正确设置:

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile "com.squareup.retrofit2:converter-scalars:2.3.0"
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

我的 ApiHelper 中有这个 Retrofit 配置:

retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

领域 4.1.1:

dependencies {
    classpath "io.realm:realm-gradle-plugin:4.1.1"
}

和我项目中的 GSON。

但是我遇到了异常:

java.lang.IllegalArgumentException: Unable to create converter for class<br> 

在请求发生之前来自 ApiHelper。

解释:
这个例外实际上与改造无关(但大多数答案都与改造配置有关)。它关于领域。从 4.0 版开始,他们增加了对 RealmList of Primitives 的支持。我的响应类包含这样的字段:

@SerializedName("bad_habits")
private RealmList<Integer> badHabitIds;

实际上这就是异常的原因!领域文档说

原语列表不支持列表列表、查询和导入 使用 Realm.create*FromJson API。

但这对我来说似乎不清楚。因此,如果您遇到此类异常并且您已设置好所有内容(我的意思是 Retrofit/GSON/gradle.build),很可能是由于使用了原语列表。支持它们,但不支持反序列化。

【问题讨论】:

    标签: android gson realm retrofit retrofit2


    【解决方案1】:

    限制是针对 createObjectFromJson()createAllFromJson() 方法,它与 GSON 如何尝试(或在这种情况下不)反序列化它无关。

    您很可能可以为您的 GSON 实例定义一个类型适配器,它会解决问题。

    Gson gson = new GsonBuilder()
        .setExclusionStrategies(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return f.getDeclaringClass().equals(RealmObject.class); // is this still needed?
            }
    
            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        })
        .registerTypeAdapter(new TypeToken<RealmList<Integer>>() {}.getType(), new TypeAdapter<RealmList<Integer>>() {
    
            @Override
            public void write(JsonWriter out, RealmList<Integer> value) throws IOException {
                // Ignore for now
            }
    
            @Override
            public RealmList<Integer> read(JsonReader in) throws IOException {
                RealmList<Integer> list = new RealmList<Integer>();
                in.beginArray();
                while (in.hasNext()) {
                    list.add(in.nextInt());
                }
                in.endArray();
                return list;
            }
        })
        .create();
    

    【讨论】:

    • 我就是这样做的。对于 RealmList 也是如此。有趣的是官方文档没有记录这种方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2019-07-25
    相关资源
    最近更新 更多