How to convert hashMap to json object in scala?

I want to convert a hashmap to a json object, my hashmap structure looks like this:

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

bt does not work.

+4
source share
4 answers

Try the following:

Ok(Json.toJson(response.toMap))

This will convert your HashMapto Map, which can be written as json without additional code.

+4
source

An alternative solution would be to use JSON4. [Https://github.com/json4s/json4s] As an added gain, it gives you a nice DSL, the ability 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}
+3
source

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

Ok(json.toJson(data.toMap))
+1
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
}

:

{"0":{"Address":"strt1","Mobile":"98974"}}
0

Source: https://habr.com/ru/post/1535353/


All Articles