您可以创建一个新结构(在这种情况下,我们将调用 result)并将其传递给 Gson 序列化:
fun main() {
val structure: Set<List<Map<String, Any>>> = setOf(
listOf(
mapOf("id" to "obj1Id", "property2" to listOf(setOf("element1"), setOf("element2"))),
mapOf("id" to "obj2Id", "property2" to listOf(setOf("element1"), setOf("element2"))),
mapOf("propertyName3" to "propertyValue3"),
mapOf("propertyName4" to "propertyValue4"),
)
)
println(structure)
// Outputs [[{id=obj1Id, property2=[[element1], [element2]]}, {id=obj2Id, property2=[[element1], [element2]]}, {propertyName3=propertyValue3}, {propertyName4=propertyValue4}]]
// Creates a hash map where we'll add the entries of the original structure
val result: MutableMap<String, Any> = mutableMapOf()
// Iterating over each list inside the first-nested level
structure.forEach { list ->
// Iterating over each map inside the second-nested level
list.forEach { map ->
// Check if this map has an `id` key
// If it has, evaluate to its value, else to null
val idValue = map["id"] as String?
// If there is an `id` key
if (idValue != null) {
// Add its value to its respective property
result[idKey] = map.filterKeys { key -> key != "id" }
// Or, if you need to add only the "property2" key:
// result[idKey] = mapOf("property2" to map["property2"])
} else {
// Add all these entries to the result map
result.putAll(map)
// Or, if you need to add only the keys starting with "propertyName":
// map.filterKeys { key -> key.startsWith("propertyName") }.forEach(result::put)
}
}
}
println(result)
// Outputs {obj1Id={property2=[[element1], [element2]]}, obj2Id={property2=[[element1], [element2]]}, propertyName3=propertyValue3, propertyName4=propertyValue4}
}