How to convert Scala Map into JSON String? How to convert Scala Map into JSON String? json json

How to convert Scala Map into JSON String?


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

Output:

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

Alternative way:

import org.json4s.native.Jsonimport org.json4s.DefaultFormatsJson(DefaultFormats).write(m)


val mapper = new ObjectMapper()mapper.writeValueAsString(Map("a" -> 1))

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

==============================

import com.fasterxml.jackson.module.scala.DefaultScalaModuleval mapper = new ObjectMapper()mapper.registerModule(DefaultScalaModule)mapper.writeValueAsString(Map("a" -> 1))

result> {"a":1}


You need to tell jackson how to deal with scala objects: mapper.registerModule(DefaultScalaModule)