Skip to content

Instantly share code, notes, and snippets.

@makiftutuncu
Last active July 13, 2020 09:27
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save makiftutuncu/3d5e1110ff3e290ee8def33fbacabdeb to your computer and use it in GitHub Desktop.
Extension methods for Jackson Json for typesafe Json handling in Kotlin
import com.fasterxml.jackson.databind.JsonNode
object JsonExtensions {
fun JsonNode.objectAt(key: String): JsonNode? = this.takeIf { it.isObject }?.get(key)?.takeIf { it.isObject }
fun JsonNode.arrayAt(key: String): JsonNode? = this.takeIf { it.isObject }?.get(key)?.takeIf { it.isArray }
fun JsonNode.booleanAt(key: String): Boolean? = this.takeIf { it.isObject && it.has(key) }?.get(key)?.takeIf { it.isBoolean }?.asBoolean()
fun JsonNode.intAt(key: String): Int? = this.takeIf { it.isObject && it.has(key) }?.get(key)?.takeIf { it.isIntegralNumber }?.asInt()
fun JsonNode.longAt(key: String): Long? = this.takeIf { it.isObject && it.has(key) }?.get(key)?.takeIf { it.isIntegralNumber }?.asLong()
fun JsonNode.doubleAt(key: String): Double? = this.takeIf { it.isObject && it.has(key) }?.get(key)?.takeIf { it.isFloatingPointNumber }?.asDouble()
fun JsonNode.stringAt(key: String): String? = this.takeIf { it.isObject && it.has(key) }?.get(key)?.takeIf { it.isTextual }?.asText()
fun JsonNode.objectAt(index: Int): JsonNode? = this.takeIf { it.isArray }?.get(index)?.takeIf { it.isObject }
fun JsonNode.arrayAt(index: Int): JsonNode? = this.takeIf { it.isArray }?.get(index)?.takeIf { it.isArray }
fun JsonNode.booleanAt(index: Int): Boolean? = this.takeIf { it.isArray && index < it.size() }?.get(index)?.takeIf { it.isBoolean }?.asBoolean()
fun JsonNode.intAt(index: Int): Int? = this.takeIf { it.isArray && index < it.size() }?.get(index)?.takeIf { it.isIntegralNumber }?.asInt()
fun JsonNode.longAt(index: Int): Long? = this.takeIf { it.isArray && index < it.size() }?.get(index)?.takeIf { it.isIntegralNumber }?.asLong()
fun JsonNode.doubleAt(index: Int): Double? = this.takeIf { it.isArray && index < it.size() }?.get(index)?.takeIf { it.isFloatingPointNumber }?.asDouble()
fun JsonNode.stringAt(index: Int): String? = this.takeIf { it.isArray && index < it.size() }?.get(index)?.takeIf { it.isTextual }?.asText()
fun JsonNode.values(): List<JsonNode>? = this.takeIf { it.isArray }?.elements()?.asSequence()?.toList()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment