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

com.jtransc.json.json.kt Maven / Gradle / Ivy

package com.jtransc.json

import com.jtransc.lang.Typer

object Json {
	fun decode(str: String): JsonObject = JsonObject(JsonReader(str).readObject())
	fun decodeAny(str: String): Any? = JsonReader(str).readValue()
	fun encode(data: Map<*, *>, prettify: Boolean = false): String = JsonWriter(prettify).writeObject(data).toString()
	fun encodeAny(data: Any?, prettify: Boolean = false): String = JsonWriter(prettify).writeValue(data).toString()

	@Deprecated("", ReplaceWith("Json.decodeTo(str, clazz)"))
	fun  decodeValue(str: String, clazz: Class): T = decodeTo(str, clazz)

	fun  decodeTo(str: String, clazz: Class): T = Typer.toTyped(decodeAny(str), clazz)
	fun  encodeFrom(value: T?, prettify: Boolean = false): String = JsonWriter(prettify).writeValue(Typer.fromTyped(value)).toString()

	inline fun  decodeTo(str: String): T = decodeTo(str, T::class.java)
	//inline fun  encodeFrom(obj: T, prettify: Boolean = false): String = encodeFrom(obj, prettify)
}

class JsonObject(val map: Map<*, *>) : Map by map as Map {
	constructor(str: String) : this(Json.decode(str))

	fun getString(key: String): String = map[key] as String
	fun getJsonObject(key: String): JsonObject = JsonObject(map[key] as Map<*, *>)
	fun getArray(key: String): List<*> = (map[key] as Iterable<*>).toList()
	fun getNumber(key: String): Double = (map[key] as Number).toDouble()
	fun getInteger(key: String): Int = (map[key] as Number).toInt()
	fun getBoolean(key: String): Boolean = map[key] as Boolean
	fun getValue(key: String): Any? = map[key]
	fun encode(prettify: Boolean = false): String = Json.encode(map, prettify)
	fun encodePrettily(): String = encode(prettify = true)
	override fun toString(): String = encode()
	inline fun  to(): T = Typer.toTyped(this, T::class.java)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy