Kotlin如何将JSONObject或Map序列化为键排序的JSON字符串
方案1:使用Gson实现(推荐,代码最简洁)
Gson从2.8.0版本开始内置了全局键排序配置,开启后会自动对所有层级的键执行自然排序,无需自行实现递归逻辑:
- 先在模块级build.gradle引入Gson依赖:
dependencies { implementation 'com.google.code.gson:gson:2.10.1' }
- 序列化代码示例:
val gson = GsonBuilder() .sortKeys() // 核心配置:开启所有层级键排序 // 不需要格式化空格可删除下一行,输出会是压缩无空格格式 .setPrettyPrinting() .create() val mapObject = mapOf<String, Any>( "b" to arrayOf( "bb", mapOf<String, Any>( "bbb" to "bbb", "aaa" to "aaa" ), "aa" ), "a" to "a" ) // 直接序列化Map即可得到排序后的JSON字符串 val sortedJson = gson.toJson(mapObject) println(sortedJson)
输出结果完全符合预期:
{"a": "a", "b": ["bb", {"aaa": "aaa", "bbb": "bbb"}, "aa"]}
方案2:纯原生org.json实现(无第三方依赖)
如果不想引入额外库,可以写递归扩展函数手动处理所有层级的排序:
import org.json.JSONArray import org.json.JSONObject fun JSONObject.toSortedString(): String { // 先排序当前层级的键 val sortedKeys = keys().asSequence().toList().sorted() val sortedMap = sortedKeys.associateWith { key -> when (val value = get(key)) { // 嵌套JSONObject递归处理 is JSONObject -> value.toSortedMap() // 遍历数组元素处理嵌套对象 is JSONArray -> value.map { element -> if (element is JSONObject) element.toSortedMap() else element } else -> value } } return JSONObject(sortedMap).toString() } private fun JSONObject.toSortedMap(): Map<String, Any?> { return keys().asSequence().toList().sorted().associateWith { key -> when (val value = get(key)) { is JSONObject -> value.toSortedMap() is JSONArray -> value.map { element -> if (element is JSONObject) element.toSortedMap() else element } else -> value } } } private inline fun <T> JSONArray.map(transform: (Any?) -> T): List<T> { val result = mutableListOf<T>() for (i in 0 until length()) { result.add(transform(get(i))) } return result }
使用方式:
val jsonObject = JSONObject(mapObject) println(jsonObject.toSortedString())
内容的提问来源于stack exchange,提问作者elsonwx
相关产品推荐
相关产品推荐

