I am writing a RESTful interface and I would like to marshall and unmarshall JSON ready for Ember Data. The wrinkle is that Ember Data wants the entity name and the two libraries I've tried, spray-json and json4s, don't appear to do this easily.
Desired Ember Data format
{
"coursePhoto": {
"photoId": 1
}
}
Current default format:
{"photoId":15}
This should come from a case class:
case class CoursePhoto(photoId: Long)
I did get it running with the following custom code:
object PtolemyJsonProtocol extends DefaultJsonProtocol {
implicit object CoursePhotoFormat extends RootJsonFormat[CoursePhoto] {
def write(cp: CoursePhoto) =
JsObject("CoursePhoto" -> JsObject("photoId" -> JsNumber(cp.photoId)))
def read(value: JsValue) = value match {
case coursePhotoJsObject: JsObject => {
CoursePhoto(coursePhotoJsObject.getFields("CoursePhoto")(0).asJsObject
.getFields("photos")(0).asInstanceOf[JsArray].elements(0)
.asInstanceOf[JsNumber].value.toLong)
}
case _ => deserializationError("CoursePhoto expected")
}
}
That code seems horrifyingly fragile and ugly with all the asInstanceOf
and (0)
.
Given that I'm writing in Spray with Scala what's the nice way to get named root JSON output? I am quite happy to do this with any JSON library that integrates nicely with Spray and is reasonably performant.
This problem made me wonder if it were possible to do it in a re-usable way. I believe I've figured out a reasonable way to do this for multiple types.
Is the following solving your problem?