scalaMap转JSON字符串和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
GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2d42229f * Support BSON uint64 de/serialization Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com> * Treat 0x11 as uint64 and not timestamp specific Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com> --------- Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com> 3 天前
1809b3d8 Signed-off-by: Niels Lohmann <mail@nlohmann.me> 3 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐