gson 如何获取对象的非空值

bbuxkriu  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(141)

我需要创建一个对象json的2个关键字,我不知道。
我目前的结构是:

{
[  {id: obj1Id , property2: [{element1}, {element2}]},
   {id: obj2Id , property2: [{element1}, {element2}]},
   {propertyName3: propertyValue3 },
   {propertyName4: propertyValue4 }
]

}

我需要把它转换成如下形式的json:

{ obj1Id: {property2: [{element1}, {element2}]}},
    obj2Id: {property2: [{element1}, {element2}]}},
    propertyName3: propertyValue3,
    propertyName4: propertyValue4
  }

是否有一种简便的方法可以实现这一点,而无需检查propertyName3和propertyName4是否存在于原始结构中?
我不知道“obj1Id”和“obj2Id”的实际字符串是什么,我也不关心。

tjvv9vkg

tjvv9vkg1#

你可以创建一个新的结构(在本例中,我们将调用result),并将其传递给Gson serialize:

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}
}

相关问题