Question

I want to convert hashmap into json object, my hashmap structure is look like this:

def res=Action{ implicit request=>
  var response=new HashMap[String,Map[String,String]]
  response=//etc .......
  .
  .
  .
  Ok(write(response))
}

bt its not working .

Was it helpful?

Solution

Try this:

Ok(Json.toJson(response.toMap))

This would convert your HashMap to a Map which can be written as json without additional code.

OTHER TIPS

An alternative solution would be to use JSON4s. [https://github.com/json4s/json4s] As additional gain it gives you a nice DSL, the abilitity to use Jackson or not and a great way to deserialize JSON.

scala> import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization

scala> implicit val formats = Serialization.formats(NoTypeHints)
formats: org.json4s.Formats{val dateFormat: org.json4s.DateFormat; val typeHints:org.json4s.TypeHints} = org.json4s.Serialization$$anon$1@f40c08d

scala> Serialization.write(Map("test" -> "a", "test 2" -> 2))
res1: String = {"test":"a","test 2":2}

Try like this

val data = response.map(value=> value._1 -> Json.toJson(value._2))

Ok(json.toJson(data.toMap))
You can try like this....

var ls: ListBuffer[(String, Map[String, String])] = ListBuffer()
val res = list1.toList.iterator

while (res.hasNext) {

  ls += (("id", getMyMap().toMap))
}
println(ls);
ls.toList
ok(write(ls.toMap))


def getMyMap(): scala.collection.mutable.Map[String, String] = {

var m=scala.collection.mutable.Map("Address" -> "strt1", "Mobile" -> 98974)
 m
}

Output:

{"0":{"Address":"strt1","Mobile":"98974"}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top