Search code examples
jsonscalaserializationjson4s

With json4s how to add field on-the-fly during serialization


I have a case class which has several DateTime fields. While using json4s to serialize it I want to serialize each of these fields as 2 separated fields - one in formatted datetime string and the other one in unix timestamp.

So for example the case class is:

case class Event {
    name: String,
    start: DateTime
}

For an object:

val event = Event("foo", DateTime.now)

I want the serialized json string to be:

{
    "name": "foo",
    "start": "2014-04-01T09:00:00+0000",
    "startUnixtime": 1396342800
}

I've tried FieldSerializer and CustomSerializer but couldn't get it work.


Solution

  • That should work:

    import org.json4s.CustomSerializer
    import org.json4s.JsonDSL.WithBigDecimal._
    import org.json4s.native.Serialization._
    
    object EventSerializer extends CustomSerializer[Event](format =>
      ( PartialFunction.empty,
        {
          case Event(name, start) =>
            ( "name" -> name ) ~
            ( "start" -> stringFormat(start) ) ~
            ( "startUnixtime" -> unixtimeFormat(start) )
        }))
    

    as long as you have methods to serialize start to your date format and to unixtime format.

    Does this solve your problem ?