Skip to content

Instantly share code, notes, and snippets.

@Zhuinden
Forked from bclymer/HttpClient.kt
Last active January 15, 2017 22:40
Show Gist options
  • Save Zhuinden/2b5f43e53856d06f00da465e7d6f3548 to your computer and use it in GitHub Desktop.
Save Zhuinden/2b5f43e53856d06f00da465e7d6f3548 to your computer and use it in GitHub Desktop.
Kotlin Realm Primitive Arrays Workaround
// originally from https://gist.github.com/bclymer/f569fffb41bab046c2d1
val realmStringArrayType = object : TypeToken<RealmStringArray>() {}.type
val gson = GsonBuilder()
.setExclusionStrategies(object : ExclusionStrategy {
override fun shouldSkipClass(clazz: Class<*>?): Boolean {
return false
}
override fun shouldSkipField(f: FieldAttributes?): Boolean {
return f?.declaringClass?.equals(RealmObject::class.java) == true
}
})
.registerTypeAdapter(realmStringArrayType, object : TypeAdapter<RealmStringArray>() {
override fun write(out: JsonWriter?, value: RealmStringArray?) {
// ignore
}
override fun read(inJson: JsonReader?): RealmStringArray? {
if (inJson != null) {
val realmStringArray = RealmStringArray()
val StringList = arrayListOf<String>()
inJson.beginArray()
while (inJson.hasNext()) {
StringList.add(inJson.nextString())
}
inJson.endArray()
realmStringArray.joinedStrings = StringList.joinToString(",,,,")
return realmStringArray
}
return null
}
})
.create()
// originally from https://gist.github.com/bclymer/f569fffb41bab046c2d1
import io.realm.RealmObject
public fun RealmStringArray.toList(): List<String> {
if (joinedStrings != null) {
return joinedStrings!!.split(",,,,")
} else {
return listOf()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment