How to serialize Scala Map to Json in PlayFramework?

nishnet2002 picture nishnet2002 · Apr 24, 2014 · Viewed 10.2k times · Source

Looks like Play Json Library is unable to serialize Scala Collections. Is there any alternative. I just need to dump the data from a map.

import scala.concurrent._
import play.api.libs.ws._
import scala.concurrent.ExecutionContext.Implicits.global
import play.libs.Json

object temp {

        // Correct Serialization
        val javaMap = new java.util.HashMap[String, String]()

        javaMap.put("Abc", "Def")

        // Outputs: res1: String = {"Abc":"Def"}
        Json.stringify(Json.toJson(javaMap))


        // Incorrect Serialization
        val scalaMap = Map("Abc" -> "Def")           //> scalaMap  : scala.collection.immutable.Map[String,String] = Map(Abc -> Def)

        // Output: res2: String = {"empty":false,"traversableAgain":true}
        Json.stringify(Json.toJson(scalaMap))       //> res2: String = {"empty":false,"traversableAgain":true}

    }

Answer

Ryan picture Ryan · Apr 24, 2014

You're importing the wrong JSON library.

import play.api.libs.json._