Don't serialize empty metas

This commit is contained in:
Alexander Nozik 2021-08-01 20:27:43 +03:00
parent b404615145
commit 90a92c4121
2 changed files with 19 additions and 13 deletions

View File

@ -32,17 +32,22 @@ private fun Meta.toJsonWithIndex(descriptor: MetaDescriptor?, index: String?): J
} else {
val pairs: MutableList<Pair<String, JsonElement>> = items.entries.groupBy {
it.key.body
}.mapTo(ArrayList()) { (body, list) ->
}.mapNotNullTo(ArrayList()) { (body, list) ->
val childDescriptor = descriptor?.children?.get(body)
if (list.size == 1) {
val (token, element) = list.first()
//do not add empty element
if (!element.isEmpty()) {
val child: JsonElement = element.toJsonWithIndex(childDescriptor, token.index)
body to child
} else null
} else {
val elements: List<JsonElement> = list.sortedBy { it.key.index }.mapIndexed { index, entry ->
val elements: List<JsonElement> = list.sortedBy { it.key.index }.mapIndexedNotNull { index, entry ->
if (!entry.value.isEmpty()) {
//Use index if it is not equal to the item order
val actualIndex = if (index.toString() != entry.key.index) entry.key.index else null
entry.value.toJsonWithIndex(childDescriptor, actualIndex)
} else null
}
body to JsonArray(elements)
}
@ -55,7 +60,7 @@ private fun Meta.toJsonWithIndex(descriptor: MetaDescriptor?, index: String?): J
//Add value if needed
if (value != null) {
pairs += Meta.VALUE_KEY to value!!.toJson(null)
pairs += Meta.VALUE_KEY to value!!.toJson(descriptor)
}
JsonObject(pairs.toMap())

View File

@ -197,7 +197,8 @@ public fun Meta.nodeSequence(): Sequence<Pair<Name, Meta>> = sequence {
public operator fun Meta.iterator(): Iterator<Pair<Name, Meta>> = nodeSequence().iterator()
public fun Meta.isEmpty(): Boolean = this === Meta.EMPTY || (value == null && items.isEmpty())
public fun Meta.isEmpty(): Boolean = this === Meta.EMPTY
|| (value == null && (items.isEmpty() || items.values.all { it.isEmpty() }))
/* Get operations*/