Last active
November 19, 2016 02:49
-
-
Save chronodm/7684755 to your computer and use it in GitHub Desktop.
Custom formatters for JodaTime DateTime and various case classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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