Map[String,Any] to compact json string using json4s

后端 未结 2 1633
谎友^
谎友^ 2020-12-14 22:19

I am currently extracting some metrics from different data sources and storing them in a map of type Map[String,Any] where the key corresponds to the metric nam

相关标签:
2条回答
  • 2020-12-14 22:34

    Since you are actually only looking for the JSON string representation of myMap, you can use the Serialization object directly. Here is a small example (if using the native version of json4s change the import to org.json4s.native.Serialization):

    EDIT: added formats implicit

     import org.json4s.jackson.Serialization
    
     implicit val formats = org.json4s.DefaultFormats
    
     val m: Map[String, Any] = Map(
       "name "-> "joe",
       "children" -> List(
         Map("name" -> "Mary", "age" -> 5),
         Map("name" -> "Mazy", "age" -> 3)
       )
     )
     // prints {"name ":"joe","children":[{"name":"Mary","age":5},{"name":"Mazy","age":3}]}
     println(Serialization.write(m)) 
    
    0 讨论(0)
  • 2020-12-14 22:40

    json4s has method for it.

    pretty(render(yourMap))
    
    0 讨论(0)
提交回复
热议问题