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)
)
)
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
}
]
}
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)
Result:
{"empty":false,"traversableAgain":true}
I don't understand why I got that result.
If you're working with a well-defined data model, why not define case classes and use Play JSON macros to handle conversion? i.e.
You need to tell jackson how to deal with scala objects:
mapper.registerModule(DefaultScalaModule)
One thing you can do using the Jackson library is to use a java HashMap object, instead of a Scala one. Then you can basically use the same "without success" code you already wrote.
returns
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:
--Updating to include the full example--
Output:
Alternative way:
result> {"empty":false,"traversableAgain":true}
==============================
result> {"a":1}
Using
scala.util.parsing.json.JSONObject
, you only need 1 line: