Taishi-Y
8/25/2017 - 3:27 AM

CustomGsonConverter for Retrofit and Realm in Java

CustomGsonConverter for Retrofit and Realm in Java

object CustomGsonConverter {
    var token = object : TypeToken<RealmList<RealmInt>>() {}.getType()
    var gson = GsonBuilder()
            .setExclusionStrategies(object : ExclusionStrategy {
                override fun shouldSkipField(f: FieldAttributes): Boolean {
                    return f.declaringClass == RealmObject::class.java
                }

                override fun shouldSkipClass(clazz: Class<*>): Boolean {
                    return false
                }
            })
            .registerTypeAdapter(CustomGsonConverter.token, object : TypeAdapter<RealmList<RealmInt>>() {
                @Throws(IOException::class)
                override fun write(out: com.google.gson.stream.JsonWriter?, value: RealmList<RealmInt>?) {

                }

                @Throws(IOException::class)
                override fun read(`in`: com.google.gson.stream.JsonReader?): RealmList<RealmInt> {
                    val list = RealmList<RealmInt>()
                    `in`!!.beginArray()
                    while (`in`.hasNext()) {
                        list.add(RealmInt(`in`.nextInt()))
                    }
                    `in`.endArray()
                    return list
                }
            })
            .create()
}
public class RealmInt extends RealmObject {
    private Integer val;

    public RealmInt() {

    }

    public RealmInt(Integer val) {
        this.val = val;
    }

    public Integer getVal() {
        return val;
    }
}
private val api = Retrofit.Builder().
            baseUrl(baseUrl).
            client(httpClient).
            addConverterFactory(GsonConverterFactory.create(CustomGsonConverter.gson)). // add CustomGsonConverter here
            addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
            build()