Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Scala Map to Json in PlayFramework?

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}

    }
like image 436
nishnet2002 Avatar asked Apr 24 '14 01:04

nishnet2002


People also ask

What is a JSValue?

You use the JSValue class to convert basic values, such as numbers and strings, between JavaScript and Objective-C or Swift representations to pass data between native code and JavaScript code.

What is play JSON?

The Play JSON API provides implicit Writes for most basic types, such as Int , Double , String , and Boolean . It also supports Writes for collections of any type T that a Writes[T] exists. import play. json.


1 Answers

You're importing the wrong JSON library.

import play.api.libs.json._

like image 85
Ryan Avatar answered Sep 20 '22 18:09

Ryan