Skip to content

Instantly share code, notes, and snippets.

@Taishi-Y
Last active August 25, 2017 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Taishi-Y/ca4ad3ea80c11d674dd2771225416121 to your computer and use it in GitHub Desktop.
Save Taishi-Y/ca4ad3ea80c11d674dd2771225416121 to your computer and use it in GitHub Desktop.
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment