2016-08-19 1 views
0

Est-il possible avec Akka (peut-être un spray "utils"?) Pour créer un flux JSON compact à partir d'un case class comme celui-ci:Akka: comment créer un json compact sans valeurs vides?

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

construit de cette façon:

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

et obtenir un JSON sous une forme compacte qui sautera la « valeur vide » et retournera:

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

?

Répondre

2

Je suis un plus simple, mais nécessite vous pour construire votre case class avec 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"} 

    } 
} 

La réponse de kali avec l'écriture personnalisée pourrait être meilleure selon ce dont vous avez besoin.

+0

Je préférerais m'en tenir à la solution 'spray.json' car je l'utilise déjà. – Randomize

+0

Je reçois: Erreur: (10, 50) Impossible de trouver JsonWriter ou classe de type JsonFormat pour quelque chose val sth = Quelque chose ("john", None, "johnson") .JSON – Randomize

+0

Le correctif est: mettre 'MyJsonProtocol' dans un autre fichier et en plus de 'println' ajouter' import MyJsonProtocol._' – Randomize

1

Vous pouvez définir ce qui pourrait arriver au cours de la sérialisation JSON, si vous avez quelques autres « trucs » vous pouvez définir cette implicite withing un trait pour la réutilisation

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)