2016-08-19 71 views
0

是否有可能與阿卡(也許有些噴霧 「utils的」?)來構建緊湊JSON給料從case class這樣開始:Akka:如何創建一個沒有空值的緊湊json?

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

內置了這種方式:

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

並得到一個緊湊的形式,將跳過「空值」,將返回的JSON:

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

回答

2

我有一個簡單的辦法,但需要你可以用Option構建你的case class

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

    } 
} 

卡利的定製作家的答案可能會更好,這取決於你需要什麼。

+0

我寧願堅持使用'spray.json'解決方案,因爲我已經使用它了。 – Randomize

+0

我得到:錯誤:(10,50)無法找到JsonWriter或JsonFormat類型的東西 val sth =某些東西(「john」,無,「johnson」).Json – Randomize

+0

解決方法是:將MyJsonProtocol放入另一個文件並在'println'之上添加'import MyJsonProtocol._' – Randomize

1

您可以定義JSON序列化過程中可能會發生什麼,如果你有一些其他的「東西」,你可以定義這個隱含withing一個特點重用

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)