"john doe", "age" -> 18, "hasChild" -> true,-6ren">
gpt4 book ai didi

json - 如何将Scala Map转换为JSON字符串?

转载 作者:行者123 更新时间:2023-12-03 15:11:05 26 4
gpt4 key购买 nike

例如,我在Scala中具有以下Map值:

val m = Map(
"name" -> "john doe",
"age" -> 18,
"hasChild" -> true,
"childs" -> List(
Map("name" -> "dorothy", "age" -> 5, "hasChild" -> false),
Map("name" -> "bill", "age" -> 8, "hasChild" -> false)
)
)

我想将其转换为其JSON字符串表示形式:
{
"name": "john doe",
"age": 18,
"hasChild": true,
"childs": [
{
"name": "dorothy",
"age": 5,
"hasChild": false
},
{
"name": "bill",
"age": 8,
"hasChild": false
}
]
}

我目前正在使用Play框架v2.3,但该解决方案不需要使用Play JSON库,尽管如果有人可以同时提供Play和非Play解决方案,那将是一个不错的选择。

到目前为止,这是我所做的没有成功的事情:
// using jackson library
val mapper = new ObjectMapper()
val res = mapper.writeValueAsString(m)
println(res)

结果:
{"empty":false,"traversableAgain":true}

我不明白为什么我得到了这个结果。

最佳答案

作为非播放解决方案,您可以考虑使用json4s,它为jackson提供了包装器,并且易于使用。
如果您使用的是json4s,则可以使用以下方法将map转换为json:

write(m)                                        
//> res0: String = {"name":"john doe","age":18,"hasChild":true,"childs":[{"name":"dorothy","age":5,"hasChild":false},{"name":"bill","age":8,"hasChild":false}]}

-更新以包含完整的示例-
import org.json4s._
import org.json4s.native.Serialization._
import org.json4s.native.Serialization
implicit val formats = Serialization.formats(NoTypeHints)

val m = Map(
"name" -> "john doe",
"age" -> 18,
"hasChild" -> true,
"childs" -> List(
Map("name" -> "dorothy", "age" -> 5, "hasChild" -> false),
Map("name" -> "bill", "age" -> 8, "hasChild" -> false)))

write(m)

输出:
 res0: String = {"name":"john doe","age":18,"hasChild":true,"childs":[{"name" 
:"dorothy","age":5,"hasChild":false},{"name":"bill","age":8,"hasChild":false }]}

替代方式:
import org.json4s.native.Json
import org.json4s.DefaultFormats

Json(DefaultFormats).write(m)

关于json - 如何将Scala Map转换为JSON字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27948128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com