Skip to content

Instantly share code, notes, and snippets.

@drguildo
Created July 23, 2015 19:55
Show Gist options
  • Save drguildo/60267b5e804e17b2974f to your computer and use it in GitHub Desktop.
Save drguildo/60267b5e804e17b2974f to your computer and use it in GitHub Desktop.
TypeAdapter for handling cases where JSON might contain an object or array.
package io.sjm.dankbot.telegram.json
import com.google.gson.*
import io.sjm.dankbot.telegram.Chat
import io.sjm.dankbot.telegram.Update
import java.lang.reflect.Type
import java.util.*
public class ArrayOfUpdateTypeAdapter : JsonDeserializer<Array<Update>> {
@throws(JsonParseException::class)
override fun deserialize(elem: JsonElement, t: Type, context: JsonDeserializationContext): Array<Update> {
val vals = ArrayList<Update>();
if (elem.isJsonArray()) {
for (e in elem.getAsJsonArray()) {
vals.add(context.deserialize<Update>(e, javaClass<Update>()) as Update)
}
} else if (elem.isJsonObject()) {
vals.add(context.deserialize<Update>(elem, javaClass<Update>()) as Update)
}
return Array<Update>(vals.size(), { i -> vals.get(i) });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment