如何在Scala中将地图序列化为JSON? [英] How do you serialize a Map to JSON in Scala?

查看:141
本文介绍了如何在Scala中将地图序列化为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在Scala中有一个地图,如下所示:

So I have a Map in Scala like this:

val m = Map[String, String](
    "a" -> "theA",
    "b" -> "theB",
    "c" -> "theC",
    "d" -> "theD",
    "e" -> "theE"
)

我想使用lift-json将这个结构序列化成一个JSON字符串。

and I want to serialize this structure into a JSON string using lift-json.

你们中有人知道如何做吗?

Do any of you know how to do this?

推荐答案

这个怎么样?

implicit val formats = net.liftweb.json.DefaultFormats
import net.liftweb.json.JsonAST._
import net.liftweb.json.Extraction._
import net.liftweb.json.Printer._
val m = Map[String, String](
    "a" -> "theA",
    "b" -> "theB",
    "c" -> "theC",
    "d" -> "theD",
    "e" -> "theE"
)
println(compact(render(decompose(m))))

输出:

{"e":"theE","a":"theA","b":"theB","c":"theC","d":"theD"}

编辑:

对于 scala.collections.mutable.Map ,您应将其首先转换为不可变地图: .toMap

For a scala.collections.mutable.Map, you should convert it first to an immutable map: .toMap

这篇关于如何在Scala中将地图序列化为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆