commonMain.com.apollographql.apollo3.api.json.JsonReaders.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of apollo-api-jvm Show documentation
Show all versions of apollo-api-jvm Show documentation
Apollo GraphQL API classes
@file:JvmName("-JsonReaders")
package com.apollographql.apollo3.api.json
import com.apollographql.apollo3.annotations.ApolloInternal
import okio.BufferedSource
import kotlin.jvm.JvmName
fun BufferedSource.jsonReader(): JsonReader {
return BufferedSourceJsonReader(this)
}
fun Map.jsonReader(): JsonReader {
return MapJsonReader(root = this)
}
/**
* Reads the reader and maps numbers to the closest representation possible in that order:
* - Int
* - Long
* - Double
* - JsonNumber
*/
@ApolloInternal
fun JsonReader.readAny(): Any? {
return when (val token = peek()) {
JsonReader.Token.NULL -> nextNull()
JsonReader.Token.BOOLEAN -> nextBoolean()
JsonReader.Token.LONG, JsonReader.Token.NUMBER -> guessNumber()
JsonReader.Token.STRING -> nextString()
JsonReader.Token.BEGIN_OBJECT -> {
beginObject()
val result = mutableMapOf()
while (hasNext()) {
result.put(nextName(), readAny())
}
endObject()
result
}
JsonReader.Token.BEGIN_ARRAY -> {
beginArray()
val result = mutableListOf()
while (hasNext()) {
result.add(readAny())
}
endArray()
result
}
else -> error("unknown token $token")
}
}
private fun JsonReader.guessNumber(): Any {
try {
return nextInt()
} catch (_: Exception) {
}
try {
return nextLong()
} catch (_: Exception) {
}
try {
return nextDouble()
} catch (_: Exception) {
}
return nextNumber()
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy