How to convert Scala Map into JSON String?

前端 未结 7 1808
一向
一向 2021-02-07 04:19

For example, I have this Map value in Scala:

val m = Map(
    \"name\" -> \"john doe\", 
    \"age\" -> 18, 
    \"hasChild\" -> true, 
    \"childs\" -         


        
7条回答
  •  滥情空心
    2021-02-07 04:33

    In case somebody is looking for a solution using standard libraries.

    def toJson(query: Any): String = query match {
      case m: Map[String, Any] => s"{${m.map(toJson(_)).mkString(",")}}"
      case t: (String, Any) => s""""${t._1}":${toJson(t._2)}"""
      case ss: Seq[Any] => s"""[${ss.map(toJson(_)).mkString(",")}]"""
      case s: String => s""""$s""""
      case null => "null"
      case _ => query.toString
    }
    

提交回复
热议问题