Scala-scalaMap转JSON字符串和javaMap

scalaMap转JSON字符串和javaMap

      • scalaMap转Json字符串
      • scalaMap转javaMap

scalaMap转Json字符串

使用json4s,那么只需使用以下命令即可将map转换为json:
–完整示例 –

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)

scalaMap转javaMap

import scala.collection.JavaConverters._
val scalaMap = Map("a" -> 1)
val javaMap = scalaMap.map{ case (k, v) => (k,v) }.asJava

//如果scalaMap中不需要做操作的话也可以这样:
val javaMap = scalaMap.asJava

你可能感兴趣的:(Scala)