如何将Scala Map转换为JSON字符串? [英] How to convert Scala Map into JSON String?

查看:879
本文介绍了如何将Scala Map转换为JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在Scala中具有以下Map值:

For example, I have this Map value in Scala:

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)
    )
)

我想将其转换为其JSON字符串表示形式:

I want to convert it to its JSON string representation:

{
    "name": "john doe",
    "age": 18,
    "hasChild": true,
    "childs": [
        {
            "name": "dorothy",
            "age": 5,
            "hasChild": false
        },
        {
            "name": "bill",
            "age": 8,
            "hasChild": false
        }
    ]
}

我目前正在使用Play框架v2.3,但是该解决方案不需要使用Play JSON库,尽管如果有人可以同时提供Play和非Play解决方案,那将是一个不错的选择.

I'm currenly working on Play framework v2.3, but the solution doesn't need to use Play JSON library, although it will be nice if someone can provide both Play and non-Play solution.

这是到目前为止我没有成功的事情:

This is what I have done so far without success:

// using jackson library
val mapper = new ObjectMapper()
val res = mapper.writeValueAsString(m)
println(res)

结果:

{"empty":false,"traversableAgain":true}

我不明白为什么会得到这个结果.

I don't understand why I got that result.

推荐答案

作为非播放解决方案,您可以考虑使用 json4s 它提供了一个围绕杰克逊的包装纸,并且易于使用. 如果您使用的是json4s,则只需使用以下命令即可将地图转换为json:

As a non play solution, you can consider using json4s which provides a wrapper around jackson and its easy to use. If you are using json4s then you can convert map to json just by using:

write(m)                                        
//> res0: String = {"name":"john doe","age":18,"hasChild":true,"childs":[{"name":"dorothy","age":5,"hasChild":false},{"name":"bill","age":8,"hasChild":false}]}

-正在更新以包含完整的示例-

--Updating to include the full example--

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)

这篇关于如何将Scala Map转换为JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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