I am using Json4s
to deserialize json messages. I have a case class like
case class A(id: Int, b: Option[java.sql.Date])
Whenever I try to convert a json message to case class A, I get none as the value of b
scala> read[A]("""{"id":1,"b":12345}""")
res2: A = A(1,None)
scala> read[A]("""{"id":1,"b":"12345"}""")
res3: A = A(1,None)
scala> read[A]("""{"id":1,"b":"12/12/2014"}""")
res4: A = A(1,None)
How can I fix this issue
Something along these lines (you might want to be more specific with formats). And then mix this trait in the classes which need to have access to this custom serializer.
import org.json4s.DefaultJsonFormats._
trait JsonFormats {
case object DateSerializer extends CustomSerializer[java.sql.Date](format => (
{
case JString(s) => Date.valueOf(s)
case JNull => null
},
{
case d: Date => JString(d.toString())
}
)
)
implicit val json4sFormats = native.Serialization.formats(NoTypeHints) + DateSerializer
}