Last active
August 25, 2017 03:29
-
-
Save Taishi-Y/ca4ad3ea80c11d674dd2771225416121 to your computer and use it in GitHub Desktop.
CustomGsonConverter for Retrofit and Realm in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RealmInt extends RealmObject { | |
private Integer val; | |
public RealmInt() { | |
} | |
public RealmInt(Integer val) { | |
this.val = val; | |
} | |
public Integer getVal() { | |
return val; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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