Skip to content

Instantly share code, notes, and snippets.

@makiftutuncu
Created June 20, 2020 12:46
Show Gist options
  • Save makiftutuncu/a37322928bdabea13cb8ce222b2fccb0 to your computer and use it in GitHub Desktop.
Save makiftutuncu/a37322928bdabea13cb8ce222b2fccb0 to your computer and use it in GitHub Desktop.
An almost complete JSON ADT in Kotlin
import java.math.BigDecimal
sealed class Json {
companion object {
fun `null`(): JNull = JNull
fun arr(vararg values: Json): JArray = JArray(*values)
fun obj(vararg pairs: Pair<String, Json>): JObject = JObject(*pairs)
fun bool(value: Boolean): JBoolean = JBoolean(value)
fun str(value: String): JString = JString(value)
fun byte(value: Byte): JNumber = JNumber(BigDecimal(value.toInt()))
fun short(value: Short): JNumber = JNumber(BigDecimal(value.toInt()))
fun int(value: Int): JNumber = JNumber(BigDecimal(value))
fun long(value: Long): JNumber = JNumber(BigDecimal(value))
fun float(value: Float): JNumber = JNumber(BigDecimal(value.toDouble()))
fun double(value: Double): JNumber = JNumber(BigDecimal(value))
}
}
object JNull: Json() {
override fun toString(): String = "null"
}
sealed class JPrimitive<out Value: Any>(open val value: Value): Json()
data class JBoolean(override val value: Boolean): JPrimitive<Boolean>(value) {
override fun toString(): String = value.toString()
}
data class JString(override val value: String): JPrimitive<String>(value) {
override fun toString(): String = """"${value.replace("\"", "\\\"")}""""
}
data class JNumber(override val value: BigDecimal): JPrimitive<BigDecimal>(value) {
override fun toString(): String = value.toPlainString()
}
data class JArray(val values: List<Json>): Json() {
constructor(vararg values: Json): this(values.toList())
override fun toString(): String = values.joinToString(",", "[", "]")
companion object {
val empty: JArray = JArray(emptyList())
}
}
data class JObject(val values: Map<String, Json>): Json() {
constructor(vararg pairs: Pair<String, Json>): this(pairs.toMap())
override fun toString(): String =
values.entries.joinToString(",", "{", "}") { (key, value) ->
""""${key.replace("\"", "\\\"")}":$value"""
}
companion object {
val empty: JObject = JObject(emptyMap())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment