如何将Scala Map转换为JSON字符串?

编程入门 行业动态 更新时间:2024-10-28 00:17:01
本文介绍了如何将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字符串?

本文发布于:2023-07-13 03:24:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1099796.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   如何将   Map   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!