How can I convert a json string to a scala map?

那年仲夏 提交于 2019-11-30 18:51:04

I tried the following method with json4s 3.2.11 and it works:

import org.json4s._
import org.json4s.jackson.JsonMethods._

//...
def jsonStrToMap(jsonStr: String): Map[String, Any] = {
  implicit val formats = org.json4s.DefaultFormats

  parse(jsonStr).extract[Map[String, Any]]
}

Maybe you didn't define the implicit val of type Formats? Note also that you don't need to have an implicit val within every and each method as long as it's findable in the scope.

You can use the following code to parse a JSON string into a Map[String, Any]

val jsonMap = parse(jsonString).values.asInstanceOf[Map[String, Any]]

However, this is not typesafe and hence should be used with caution when extracting values from the map.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!