Skip to content

Instantly share code, notes, and snippets.

@chronodm
Last active November 19, 2016 02:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chronodm/7684755 to your computer and use it in GitHub Desktop.
Save chronodm/7684755 to your computer and use it in GitHub Desktop.
Custom formatters for JodaTime DateTime and various case classes
package format
import model._
import spray.json._
import org.joda.time.DateTime
import org.joda.time.format.{ISODateTimeFormat, DateTimeFormatter}
/**
* @version $Id$ $Rev: 223159 $ $Date: 2013-11-27 15:12:03 -0800 (Wed, 27 Nov 2013) $
*/
object ApiFormats extends DefaultJsonProtocol {
implicit object DateTimeFormat extends RootJsonFormat[DateTime] {
val formatter = ISODateTimeFormat.basicDateTimeNoMillis
def write(obj: DateTime): JsValue = {
JsString(formatter.print(obj))
}
def read(json: JsValue): DateTime = json match {
case JsString(s) => try {
formatter.parseDateTime(s)
}
catch {
case t: Throwable => error(s)
}
case _ =>
error(json.toString())
}
def error(v: Any): DateTime = {
val example = formatter.print(0)
deserializationError(f"'$v' is not a valid date value. Dates must be in compact ISO-8601 format, e.g. '$example'")
}
}
implicit val bibFormat = jsonFormat15(Bib)
implicit val materialTypeFormat = jsonFormat2(MaterialType)
implicit val bibLevelFormat = jsonFormat2(BibLevel)
implicit val fixedFieldFormat = jsonFormat4(FixedField)
implicit val varFieldFormat = jsonFormat6(VarField)
implicit val subFieldFormat = jsonFormat2(SubField)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment