Skip to content

Instantly share code, notes, and snippets.

@dave08
Created January 9, 2019 13:24
Show Gist options
  • Save dave08/32632fe438998f845713df789115171d to your computer and use it in GitHub Desktop.
Save dave08/32632fe438998f845713df789115171d to your computer and use it in GitHub Desktop.
fun JsonReader.skipNameAndValue() {
skipName()
skipValue()
}
fun JsonReader.nextLongOrNull() =
if (peek() == JsonReader.Token.NULL) {
nextNull<Long>()
null
} else
nextLong()
fun JsonReader.nextStringAsInt() =
when(peek()) {
JsonReader.Token.STRING -> nextString().toInt()
JsonReader.Token.NULL -> nextNull<Int>()
else -> nextInt()
}
fun JsonReader.nextStringOrNull() =
if (peek() == JsonReader.Token.NULL) {
nextNull<String>()
null
} else
nextString()
/**
* Reads the next object and runs [body] for each property in it. If there is null or an array instead
* of the expected object, just ignore it.
*
* @return Boolean Returns false the object exists, but is empty
*/
inline fun JsonReader.readObject(body: JsonReader.() -> Unit): Boolean {
when(peek()) {
JsonReader.Token.NULL -> {
nextNull<Unit>()
}
JsonReader.Token.BEGIN_ARRAY -> {
readArray { }
return false
}
else -> {
beginObject()
if (peek() == JsonReader.Token.END_OBJECT) {
endObject()
return false
}
while (hasNext()) {
body()
}
endObject()
}
}
return true
}
inline fun JsonReader.readArray(body: () -> Unit) {
if (peek() == JsonReader.Token.NULL) { nextNull<Unit>(); return }
beginArray()
while (hasNext()) {
body()
}
endArray()
}
fun JsonReader.readStringArrayTo(list: MutableSet<String>) {
if (peek() == JsonReader.Token.NULL) { nextNull<Unit>(); return }
beginArray()
while (hasNext()) {
list.add(nextString())
}
endArray()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment