Search code examples
scalaakkaspray-json

Akka: how to create a compact json without empty values?


Is it possible with Akka (maybe some Spray "utils"?) to build a compact json feed starting from a case class like this:

case class Stuff (val1: String, val2: String, val3: String)

built in this way:

Stuff("one value", "", "another value")

and get a json in a compact form that will skip the "empty value" and will return:

{"val1" : "one value", "val3" : "another value"}

?


Solution

  • I got a simpler one but requires you to construct your case class with Option.

    import spray.json._
    
    case class Something(name: String, mid: Option[String], surname: String)
    
    object MyJsonProtocol extends DefaultJsonProtocol {
      implicit val sthFormat = jsonFormat3(Something)
    }
    
    object Main {
      def main(args: Array[String]): Unit = {
    
        val sth = Something("john", None, "johnson").toJson
        println(sth) // yields {"name":"john","surname":"johnson"}
    
      }
    }
    

    kali's answer with custom writer might be better depending on what you need.