Created
February 20, 2017 09:01
-
-
Save markus2610/74bb750fb22bff2b9d13501565ae8944 to your computer and use it in GitHub Desktop.
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
package de.wdv.apps.yoursingapore.core.moshi | |
import com.squareup.moshi.JsonAdapter | |
import com.squareup.moshi.JsonReader | |
import com.squareup.moshi.JsonWriter | |
import com.squareup.moshi.Types | |
import io.realm.RealmList | |
import io.realm.RealmModel | |
/* | |
* Copyright 2017 Markus Wedler. | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
class RealmListAdapter<T : RealmModel>( | |
val elementAdapter: JsonAdapter<T>) : JsonAdapter<RealmList<T>>() { | |
companion object { | |
val FACTORY: Factory = Factory { type, annotations, moshi -> | |
val rawType: Class<*> = Types.getRawType(type) | |
if (rawType == RealmList::class.java) { | |
val elementType = Types.collectionElementType(type, RealmList::class.java) | |
val elementAdapter = moshi.adapter<RealmModel>(elementType) | |
return@Factory RealmListAdapter(elementAdapter).nullSafe() | |
} | |
null | |
} | |
} | |
override fun fromJson(reader: JsonReader): RealmList<T> { | |
val result = RealmList<T>() | |
reader.beginArray() | |
while (reader.hasNext()) { | |
result.add(elementAdapter.fromJson(reader)) | |
} | |
reader.endArray() | |
return result | |
} | |
override fun toJson(writer: JsonWriter, value: RealmList<T>) { | |
writer.beginArray() | |
for (element in value) { | |
elementAdapter.toJson(writer, element) | |
} | |
writer.endArray() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment