Randomize
Randomize

Reputation: 9103

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"}

?

Upvotes: 0

Views: 443

Answers (2)

kali
kali

Reputation: 1161

You can define what might happen during the json serialization, if you'll have a few other "stuff" you can define this implicit withing a trait for reuse

import org.json4s.jackson.Serialization._
import org.json4s.{FieldSerializer, NoTypeHints}
import org.json4s.jackson.Serialization

trait EmptySpaceIgnoredJsonable {
    def toJsonWithEmptyThingies : String = {
        implicit val formats = Serialization.formats( NoTypeHints ) +
            FieldSerializer[ this.type ]( doStuffWhileSerializing() )
        write( this )
    }

    def doStuffWhileSerializing() : PartialFunction[ (String, Any), Option[ (String, Any) ] ] = {
        case (x, y : String) if !y.isEmpty => Some( x , y )
        case _ => None
    }
}

// then use it, when ever you require empty "stuff"
case class Stuff (val1: String, val2: String, val3: String) extends EmptySpaceIgnoredJsonable
val stuff = Stuff("one value", "", "another value")
println(stuff.toJsonWithEmptyThingies)

Upvotes: 1

sebszyller
sebszyller

Reputation: 853

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.

Upvotes: 2

Related Questions