Last active
July 13, 2020 09:27
Star
You must be signed in to star a gist
Extension methods for Jackson Json for typesafe Json handling in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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