Advertisement
Guest User

Custom JSON Serializer

a guest
May 17th, 2015
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.19 KB | None | 0 0
  1. import org.json4s.JsonDSL._
  2. import org.json4s.native.Serialization
  3. import org.json4s.native.Serialization.{write, read}
  4. import org.json4s.{CustomSerializer, JValue, NoTypeHints}
  5.  
  6.  
  7. object SerializationExample {
  8.  
  9.   case class Test(a: String, b: Option[Double])
  10.  
  11.   object TestSerializer extends CustomSerializer[Test](format => ( {
  12.     case jv: JValue =>
  13.       val a = (jv \ "a").extract[String]
  14.       val b = (jv \ "b").extractOpt[Double] // <-- Specify which type to extract
  15.       Test(a, b)
  16.   }, {
  17.     case tst: Test =>
  18.       tst.b match {
  19.         case Some(x) => ("a" -> "test") ~ ("b" -> x)
  20.         case None => ("a" -> "test") ~ ("b" -> "NA")
  21.       }
  22.   }))
  23.  
  24.   implicit val formats = Serialization.formats(NoTypeHints) + TestSerializer
  25.  
  26.  
  27.   def main(args: Array[String]): Unit = {
  28.     println(write(Test("test", Some(1.0))))              // {"a":"test","b":1.0}
  29.     println(read[Test]("{\"a\":\"test\",\"b\":1.0}"))    // Test(test,Some(1.0))
  30.     println(write(Test("test", None)))                   // {"a":"test","b":"NA"}
  31.     println(read[Test]("{\"a\":\"test\",\"b\":\"NA\"}")) // Test(test,None)
  32.     println(read[Test]("{\"a\":\"test\"}"))              // Test(test,None)
  33.   }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement