All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.apollographql.apollo3.api.json.JsonReaders.kt Maven / Gradle / Ivy

There is a newer version: 4.0.0-beta.7
Show newest version
@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