Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.json4s.JsonDSL._
- import org.json4s.native.Serialization
- import org.json4s.native.Serialization.{write, read}
- import org.json4s.{CustomSerializer, JValue, NoTypeHints}
- object SerializationExample {
- case class Test(a: String, b: Option[Double])
- object TestSerializer extends CustomSerializer[Test](format => ( {
- case jv: JValue =>
- val a = (jv \ "a").extract[String]
- val b = (jv \ "b").extractOpt[Double] // <-- Specify which type to extract
- Test(a, b)
- }, {
- case tst: Test =>
- tst.b match {
- case Some(x) => ("a" -> "test") ~ ("b" -> x)
- case None => ("a" -> "test") ~ ("b" -> "NA")
- }
- }))
- implicit val formats = Serialization.formats(NoTypeHints) + TestSerializer
- def main(args: Array[String]): Unit = {
- println(write(Test("test", Some(1.0)))) // {"a":"test","b":1.0}
- println(read[Test]("{\"a\":\"test\",\"b\":1.0}")) // Test(test,Some(1.0))
- println(write(Test("test", None))) // {"a":"test","b":"NA"}
- println(read[Test]("{\"a\":\"test\",\"b\":\"NA\"}")) // Test(test,None)
- println(read[Test]("{\"a\":\"test\"}")) // Test(test,None)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement