如何使用Scala将含Map的JSON转换为目标数组结构?
Scala JSON转换完整实现
输入JSON
{ "record1": { "firstName": "John", "lastName": "Doe", "locations": { "29b2f2295cd74b8cbb53db4379f0d823": "New York" } }, "record2": { "firstName": "Carol", "lastName": "Rees", "locations": { "0055bb74b4984156b821ebbea6937084": "California" } }, "record3": { "firstName": "Colin", "lastName": "Scott", "locations": { "aba67f566fc24f8a8eb3165648ca5e4f": "Toronto", "b847750c565246638dbc72cb89ead227": "London" } } }
目标JSON
{ "record1": { "firstName": "John", "lastName": "Doe", "locations": [{ "id" : "29b2f2295cd74b8cbb53db4379f0d823", "location": "New York" }] }, "record2": { "firstName": "Carol", "lastName": "Rees", "locations": [{ "id" : "0055bb74b4984156b821ebbea6937084", "location": "California" }] }, "record3": { "firstName": "Colin", "lastName": "Scott", "locations": [{ "id": "aba67f566fc24f8a8eb3165648ca5e4f", "location": "Toronto" }, { "id" : "b847750c565246638dbc72cb89ead227", "location": "London" }] } }
完整实现代码
import com.fasterxml.jackson.databind.JsonMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule // 对应输入JSON结构的case class case class PersonEntry(firstName: String, lastName: String, locations: Map[String, String]) // 对应目标JSON结构的case class case class LocationEntry(id: String, location: String) case class TargetPersonEntry(firstName: String, lastName: String, locations: List[LocationEntry]) object JsonConverter { def main(args: Array[String]): Unit = { val jsonMapper = JsonMapper.builder().addModule(DefaultScalaModule).build() val inputJson: String = """{ "record1": { "firstName": "John", "lastName": "Doe", "locations": { "29b2f2295cd74b8cbb53db4379f0d823": "New York" } }, "record2": { "firstName": "Carol", "lastName": "Rees", "locations": { "0055bb74b4984156b821ebbea6937084": "California" } }, "record3": { "firstName": "Colin", "lastName": "Scott", "locations": { "aba67f566fc24f8a8eb3165648ca5e4f": "Toronto", "b847750c565246638dbc72cb89ead227": "London" } } }""" // 解析输入JSON为Map[String, PersonEntry] val personMap: Map[String, PersonEntry] = jsonMapper.readValue(inputJson, classOf[Map[String, PersonEntry]]) // 将输入结构转换为目标结构 val targetMap: Map[String, TargetPersonEntry] = personMap.map { case (key, entry) => val locationList = entry.locations.map { case (id, loc) => LocationEntry(id, loc) }.toList key -> TargetPersonEntry(entry.firstName, entry.lastName, locationList) } // 序列化为格式化后的目标JSON并输出 val outputJson = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(targetMap) println(outputJson) } }
核心步骤说明
- 新增
LocationEntry和TargetPersonEntry两个case class,完全匹配目标JSON的嵌套结构。 - 遍历输入解析后的
PersonEntry集合,将每个locations的键值对转换为LocationEntry实例,再转成List类型。 - 使用Jackson的
writerWithDefaultPrettyPrinter()生成带格式的JSON字符串,确保输出和目标结构一致。
内容的提问来源于stack exchange,提问作者psb
相关产品推荐
相关产品推荐

