Fix json to meta mapping

This commit is contained in:
Alexander Nozik 2024-07-22 11:34:29 +03:00
parent 1f1f894e0d
commit b4ebdfe089

View File

@ -36,7 +36,7 @@ private fun Meta.toJsonWithIndex(descriptor: MetaDescriptor?, index: String?): J
val (token, element) = list.first() val (token, element) = list.first()
//do not add an empty element //do not add an empty element
val child: JsonElement = element.toJsonWithIndex(childDescriptor, token.index) val child: JsonElement = element.toJsonWithIndex(childDescriptor, token.index)
if(token.index == null) { if (token.index == null) {
body to child body to child
} else { } else {
body to JsonArray(listOf(child)) body to JsonArray(listOf(child))
@ -106,7 +106,7 @@ private fun JsonElement.toValueOrNull(descriptor: MetaDescriptor?): Value? = whe
private fun MutableMap<NameToken, SealedMeta>.addJsonElement( private fun MutableMap<NameToken, SealedMeta>.addJsonElement(
key: String, key: String,
element: JsonElement, element: JsonElement,
descriptor: MetaDescriptor? descriptor: MetaDescriptor?,
) { ) {
when (element) { when (element) {
is JsonPrimitive -> put(NameToken(key), Meta(element.toValue(descriptor))) is JsonPrimitive -> put(NameToken(key), Meta(element.toValue(descriptor)))
@ -136,12 +136,14 @@ private fun MutableMap<NameToken, SealedMeta>.addJsonElement(
Meta(childValue) Meta(childValue)
} }
} }
is JsonPrimitive -> Meta(childElement.toValue(null)) is JsonPrimitive -> Meta(childElement.toValue(null))
} }
put(NameToken(key, index), child) put(NameToken(key, index), child)
} }
} }
} }
is JsonObject -> { is JsonObject -> {
val indexKey = descriptor?.indexKey ?: Meta.INDEX_KEY val indexKey = descriptor?.indexKey ?: Meta.INDEX_KEY
val index = element[indexKey]?.jsonPrimitive?.content val index = element[indexKey]?.jsonPrimitive?.content
@ -163,14 +165,14 @@ public fun JsonObject.toMeta(descriptor: MetaDescriptor? = null): SealedMeta {
public fun JsonElement.toMeta(descriptor: MetaDescriptor? = null): SealedMeta = when (this) { public fun JsonElement.toMeta(descriptor: MetaDescriptor? = null): SealedMeta = when (this) {
is JsonPrimitive -> Meta(toValue(descriptor)) is JsonPrimitive -> Meta(toValue(descriptor))
is JsonObject -> toMeta(descriptor) is JsonObject -> toMeta(descriptor)
is JsonArray -> if (any { it is JsonObject }) { is JsonArray -> if (all { it is JsonPrimitive }) {
Meta(map { it.toValueOrNull(descriptor) ?: error("Unreachable: should not contain objects") }.asValue())
} else {
SealedMeta(null, SealedMeta(null,
linkedMapOf<NameToken, SealedMeta>().apply { linkedMapOf<NameToken, SealedMeta>().apply {
addJsonElement(Meta.JSON_ARRAY_KEY, this@toMeta, null) addJsonElement(Meta.JSON_ARRAY_KEY, this@toMeta, null)
} }
) )
} else{
Meta(map { it.toValueOrNull(descriptor) ?: kotlin.error("Unreachable: should not contain objects") }.asValue())
} }
} }