map數據json
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) ) )
指望String數據code
{ "name": "john doe", "age": 18, "hasChild": true, "childs": [ { "name": "dorothy", "age": 5, "hasChild": false }, { "name": "bill", "age": 8, "hasChild": false } ] }
方法一orm
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)
方法二ci
import org.json4s.native.Json import org.json4s.DefaultFormats Json(DefaultFormats).write(m)
方法三string
myString.substring(1, myString.length - 1) .split(",") .map(_.split(":")) .map { case Array(k, v) => (k.substring(1, k.length-1), v.substring(1, v.length-1))} .toMap
json string轉化爲mapit
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))) val a = m.values.asInstanceOf[Map[String,Any]]