Skip to content

Instantly share code, notes, and snippets.

@vinaysshenoy
Created December 30, 2017 04:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinaysshenoy/8eb019da89fda725ac84412a4a230b5d to your computer and use it in GitHub Desktop.
Save vinaysshenoy/8eb019da89fda725ac84412a4a230b5d to your computer and use it in GitHub Desktop.
Gson Extension Functions
package com.vinaysshenoy
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken.NULL
inline fun JsonReader.parseObject(keys: Set<String>, block: JsonReader.(String) -> Unit) {
beginObject()
while (hasNext()) {
val key = nextName()
if (key in keys) {
this.block(key)
} else {
skipValue()
}
}
endObject()
}
@JvmOverloads
inline fun <R> JsonReader.parseArray(block: JsonReader.() -> R, limit: Int = 0): List<R> {
val r = mutableListOf<R>()
var readCount = 0
beginArray()
while (hasNext()) {
if (limit > 0 && limit == readCount) {
skipValue()
continue
}
r.add(this.block())
readCount++
}
endArray()
return r
}
@JvmOverloads
inline fun <R> JsonReader.nullableGet(block: JsonReader.() -> R, ifNull: R? = null): R? {
return when (peek()) {
NULL -> {
skipValue()
ifNull
}
else -> this.block()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment