如何将 Scala Map 转换为 JSON 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27948128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Scala Map into JSON String?
提问by null
For example, I have this Map value in Scala:
例如,我在 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)
)
)
I want to convert it to its JSON string representation:
我想将它转换为它的 JSON 字符串表示:
{
"name": "john doe",
"age": 18,
"hasChild": true,
"childs": [
{
"name": "dorothy",
"age": 5,
"hasChild": false
},
{
"name": "bill",
"age": 8,
"hasChild": false
}
]
}
I'm currenly working on Play framework v2.3, but the solution doesn't need to use Play JSON library, although it will be nice if someone can provide both Play and non-Play solution.
我目前正在研究 Play 框架 v2.3,但该解决方案不需要使用 Play JSON 库,尽管如果有人可以提供 Play 和非 Play 解决方案会很好。
This is what I have done so far without success:
这是我迄今为止所做的没有成功的事情:
// using Hymanson library
val mapper = new ObjectMapper()
val res = mapper.writeValueAsString(m)
println(res)
Result:
结果:
{"empty":false,"traversableAgain":true}
I don't understand why I got that result.
我不明白为什么我得到这个结果。
回答by mohit
As a non play solution, you can consider using json4swhich provides a wrapper around Hymanson and its easy to use. If you are using json4s then you can convert map to json just by using:
作为非播放解决方案,您可以考虑使用json4s,它提供了 Hymanson 的包装器并且易于使用。如果您使用的是 json4s,那么您只需使用以下命令即可将地图转换为 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}]}
--Updating to include the full example--
--更新以包含完整示例--
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)
Output:
输出:
res0: String = {"name":"john doe","age":18,"hasChild":true,"childs":[{"name"
:"dorothy","age":5,"hasChild":false},{"name":"bill","age":8,"hasChild":false }]}
Alternative way:
替代方式:
import org.json4s.native.Json
import org.json4s.DefaultFormats
Json(DefaultFormats).write(m)
回答by Dima
You need to tell Hymanson how to deal with scala objects: mapper.registerModule(DefaultScalaModule)
你需要告诉Hymanson如何处理scala对象: mapper.registerModule(DefaultScalaModule)
回答by forcontents
val mapper = new ObjectMapper()
mapper.writeValueAsString(Map("a" -> 1))
result> {"empty":false,"traversableAgain":true}
结果> {"empty":false,"traversableAgain":true}
==============================
==============================
import com.fasterxml.Hymanson.module.scala.DefaultScalaModule
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
mapper.writeValueAsString(Map("a" -> 1))
result> {"a":1}
结果> {"a":1}
回答by u1516331
val mymap = array.map {
case 1 => ("A", 1)
case 2 => ("B", 2)
case 3 => ("C", 3)
}
.toMap
Using scala.util.parsing.json.JSONObject, you only need 1 line:
使用scala.util.parsing.json.JSONObject,您只需要 1 行:
import scala.util.parsing.json.JSONObject
JSONObject(mymap).toString()
回答by josephpconley
If you're working with a well-defined data model, why not define case classes and use Play JSON macros to handle conversion? i.e.
如果您正在使用定义良好的数据模型,为什么不定义案例类并使用 Play JSON 宏来处理转换?IE
case class Person(name: String, age: Int, hasChild: Boolean, childs: List[Person])
implicit val fmt = Json.format[Person]
val person = Person(...)
val jsonStr = Json.toJson(person)
回答by bill_e
One thing you can do using the Hymanson library is to use a java HashMap object, instead of a Scala one. Then you can basically use the same "without success" code you already wrote.
使用 Hymanson 库可以做的一件事是使用 java HashMap 对象,而不是 Scala 对象。然后你基本上可以使用你已经编写的相同的“没有成功”的代码。
import org.codehaus.Hymanson.map.ObjectMapper
val mapper = new ObjectMapper()
val jmap = new java.util.HashMap[String, Int]()
jmap.put("dog", 4)
jmap.put("cat", 1)
// convert to json formatted string
val jstring = mapper.writeValueAsString(jmap)
println(jstring)
returns
回报
jstring: String = {"dog":4,"cat":1}
回答by Paolo
In case somebody is looking for a solution using standard libraries.
如果有人正在寻找使用标准库的解决方案。
def toJson(query: Any): String = query match {
case m: Map[String, Any] => s"{${m.map(toJson(_)).mkString(",")}}"
case t: (String, Any) => s""""${t._1}":${toJson(t._2)}"""
case ss: Seq[Any] => s"""[${ss.map(toJson(_)).mkString(",")}]"""
case s: String => s""""$s""""
case null => "null"
case _ => query.toString
}

