This commit is contained in:
DBotThePony 2022-12-30 18:49:03 +07:00
parent 4e09fad480
commit d925f33e44
Signed by: DBot
GPG Key ID: DCC23B5715498507
2 changed files with 115 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package ru.dbotthepony.kstarbound.util
class FullJsonPath(val fullPath: String) {
init {
val delimers = fullPath.count { it == ':' }
require(delimers < 2) { "Invalid path: $fullPath" }
}
val path = fullPath.substringBefore(':')
val subpath: JsonPath
init {
if (path.any { it == ':' }) {
subpath = JsonPath(fullPath.substringAfter(':'))
} else {
subpath = JsonPath.EMPTY
}
}
}

View File

@ -0,0 +1,96 @@
package ru.dbotthepony.kstarbound.util
import com.google.common.collect.ImmutableList
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.google.gson.JsonObject
class JsonPath(val path: String) {
private class Piece(private val value: String) {
private val asNumber = value.toIntOrNull()
fun navigate(element: JsonElement): JsonElement? {
if (element is JsonObject) {
return element[value]
}
if (element is JsonArray) {
if (asNumber == null) {
return null
}
return element[asNumber]
}
return null
}
fun navigate(element: Any): Any? {
if (element is List<*>) {
if (asNumber == null) {
return null
}
return element.getOrNull(asNumber)
}
if (element is Map<*, *>) {
return element[value]
}
return null
}
}
val parts: List<String> = ImmutableList.copyOf(path.split('.'))
private val pieces: List<Piece> = ImmutableList.copyOf(parts.map { Piece(it) })
fun navigate(element: JsonElement): JsonElement? {
var current: JsonElement? = element
for (piece in pieces) {
if (current == null)
return null
current = piece.navigate(current)
}
return current
}
fun navigate(element: List<Any>): Any? {
var current: Any? = element
for (piece in pieces) {
if (current == null)
return null
current = piece.navigate(current)
}
return current
}
fun navigate(element: Map<Any, Any>): Any? {
var current: Any? = element
for (piece in pieces) {
if (current == null)
return null
current = piece.navigate(current)
}
return current
}
val isEmpty: Boolean
get() = path.isEmpty()
val isBlank: Boolean
get() = path.isBlank()
companion object {
val EMPTY = JsonPath("")
}
}