Scala map json 互转demo
import scala.util.parsing.json._
object JsonTest {
def main(args: Array[String]): Unit = {
val map = Map("a" -> "b", "c" -> "d")
println(map)
// map to json string
val str = mapToJson(map)
println(str)
// string to map
val m = jsonToMap(str)
println(m.toString)
}
def mapToJson(map: Map[String, String]): String = {
JSONObject(map).toString()
}
def jsonToMap(json: String): Map[String, String] = {
JSON.parseFull(json).get.asInstanceOf[Map[String,String]]
}
}
运行结果
Map(a -> b, c -> d)
{"a" : "b", "c" : "d"}
Map(a -> b, c -> d)
网友评论