Created
December 30, 2017 04:31
-
-
Save vinaysshenoy/8eb019da89fda725ac84412a4a230b5d to your computer and use it in GitHub Desktop.
Gson Extension Functions
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 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