在Scala中,你可以使用递归的方式来实现将嵌套结构的JSON转换为扁平化的形式。以下是一个通用的方法示例:
import scala.collection.mutable
def flattenJson(json: Map[String, Any], prefix: String = ""): Map[String, Any] = {
val result = mutable.Map[String, Any]()
def flatten(value: Any, keyPrefix: String): Unit = value match {
case mapValue: Map[String, Any] =>
mapValue.foreach { case (k, v) => flatten(v, s"$keyPrefix$k.") }
case listValue: Seq[Map[String, Any]] =>
listValue.zipWithIndex.foreach { case (item, index) => flatten(item, s"$keyPrefix$index.") }
case _ =>
result.put(keyPrefix.dropRight(1), value)
}
json.foreach { case (key, value) => flatten(value, s"$prefix$key.") }
result.toMap
}
val json = """
{
"resultCode": "0",
"resultMsg": "处理成功",
"tacheGroup": [{
"actualTacheInfo": [{
"number": "830",
"tacheName": "三层VPN调度自动",
"tacheCode": "MPLS-DIS-AUTO",
"tacheId": "1693183",
"caller": "202104002",
"responder": "202104002",
"tacheStatus": "0",
"areaId": "",
"isAlarm": "2008045002",
"tacheType": "0",
"startTime": "2024-06-21 10:02:45",
"endTime": "2024-06-21 10:02:49",
"errorMsg": "",
"errorMsgCode": "",
"errorHandleSysCode": "",
"errorRpbHandleSysCode": "",
"errorRpbHandleSysName": "",
"provincialContacts": "",
"provincialNum": "",
"provincialMail": "",
"child": []
}]
}]
}
"""
// 解析JSON
import scala.util.parsing.json.JSON
val parsedJson = JSON.parseFull(json)
parsedJson match {
case Some(map: Map[String, Any]) =>
// 转换为扁平化的形式
val flattenedJson = flattenJson(map)
// 打印结果
flattenedJson.foreach { case (key, value) => println(s"$key -> $value") }
case _ =>
println("Invalid JSON format")
}
在这个例子中,首先将JSON字符串解析为一个Map[String, Any]
对象,然后使用flattenJson
方法将其转换为扁平化的形式。最后,通过遍历输出每个键值对来打印结果。请注意,你需要导入scala.util.parsing.json.JSON
类来解析JSON字符串。
内容由零声教学AI助手提供,问题来源于学员提问