You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中将Map类型对象转换为指定格式的对象数组?

问题描述

现有如下JSON结构:

{
  "107": "First",
  "125": "Second",
  "130": "Third",
  "141": "Fourth"
}

需要将其转换为如下格式的对象数组:

[
  {
    "107": "First"
  },
  {
    "125": "Second"
  },
  {
    "130": "Third"
  },
  {
    "141": "Fourth"
  }
]
Kotlin实现方案

核心实现逻辑非常简单:先将原始JSON解析为键值对Map,再遍历Map的每个键值对,逐个封装为仅含单个键值对的对象,最后组装为数组即可。

以下是两种常用JSON库的实现示例:

方案1:使用Kotlin官方序列化库 kotlinx.serialization

import kotlinx.serialization.json.*
import kotlinx.serialization.encodeToString

fun convertJson(inputJson: String): String {
    // 解析输入JSON为JsonObject对象
    val inputObj = Json.parseToJsonElement(inputJson).jsonObject
    // 遍历每个键值对,生成单键JsonObject的列表
    val resultList = inputObj.entries.map { (key, value) ->
        buildJsonObject { put(key, value) }
    }
    // 序列化列表为格式化的目标JSON字符串
    return Json { prettyPrint = true }.encodeToString(resultList)
}

// 调用测试
fun main() {
    val input = """
        {
          "107": "First",
          "125": "Second",
          "130": "Third",
          "141": "Fourth"
        }
    """.trimIndent()
    println(convertJson(input))
}

如果只需要内存中的对象结构,不需要输出为JSON字符串,直接拿到resultList即可使用,无需后续序列化操作。

方案2:使用Jackson序列化库

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule

fun convertJsonWithJackson(inputJson: String): String {
    val objectMapper = ObjectMapper().registerKotlinModule()
    // 解析原始JSON为Map结构
    val inputMap: Map<String, String> = objectMapper.readValue(inputJson)
    // 转换为单键Map组成的列表
    val resultList = inputMap.map { (key, value) -> mapOf(key to value) }
    // 序列化为格式化的JSON字符串
    return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultList)
}

内容的提问来源于stack exchange,提问作者Islam Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 08:54:01