Search code examples
jsonscalaseqspray-json

Use Spray Json to convert 2D sequence of Any into Json


I am trying to understand Spray Json and very new to Scala. I have Seq(Seq("abc", 123, false, null), Seq("def", 45, "1234", 'C')) so a Seq[Seq[Any]]. I am not sure how to go about this and I cannot find any examples online.

case class SeqFormat(Seq[Seq[Any]]) => {
    // something that would convert to Seq[Seq[String]] 
    //which will would return a Json like this
    //[["abc", "123", "false", "null"],["def", "45", "1234", "C"]]
}

I tried

val someSeq = [["abc", "123", "false", "null"],["def", "45", "1234", "C"]]
val myObj = someSeq.toJson
// This gives me an error saying Any is not valid

I would appreciate any hints or snippets to help me understand this.


Solution

  • You could use an encoder such as:

    import spray.json._
    import DefaultJsonProtocol._
    
    implicit object AnyJsonFormat extends JsonFormat[Any] {
    
      def write(x: Any) =
        try {
          x match {
            case n: Int    => JsNumber(n)
            case s: String => JsString(s)
            case c: Char   => JsString(c.toString)
            case _         => JsString("null")
          }
        } catch {
          case _: NullPointerException => JsString("null")
        }
    
      def read(value: JsValue) = ???
    }
    

    Which you can use as follow:

    val input = Seq(Seq("abc", 123, false, null), Seq("def", 45, "1234", 'C'))
    println(input.toJson)
    

    In order to get:

    [["abc",123,"null","null"],["def",45,"1234","C"]]
    

    This is an adapted version of this post: Serialize Map[String, Any] with spray json

    Notice the NullPointerException handling for the null case.