Skip to content

Instantly share code, notes, and snippets.

@analytically
Created July 9, 2012 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save analytically/3077691 to your computer and use it in GitHub Desktop.
Save analytically/3077691 to your computer and use it in GitHub Desktop.
Spray XStream marshalling support
import cc.spray.typeconversion.{DefaultMarshallers, SimpleMarshaller, SimpleUnmarshaller, DefaultUnmarshallers}
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.StaxDriver
import cc.spray.http._
import MediaTypes._
import HttpCharsets._
import cc.spray.json._
import cc.spray.SprayBaseSettings
import cc.spray.http.ContentTypeRange
/**
* @author Mathias Bogaert
*/
trait SprayXmlJsonSupport {
private val xstream = XStreamConversions(new XStream(new StaxDriver()))
xstream.autodetectAnnotations(true)
implicit def sprayXmlJsonUnmarshaller[A: RootJsonReader] = new SimpleUnmarshaller[A] {
val canUnmarshalFrom = ContentTypeRange(`text/xml`) :: ContentTypeRange(`application/json`) :: Nil
def unmarshal(content: HttpContent) = protect {
content.contentType.mediaType match {
case MediaTypes.`application/json` => {
val jsonSource = DefaultUnmarshallers.StringUnmarshaller(content).right.get
val json = JsonParser(jsonSource)
jsonReader[A].read(json)
}
case _ => {
val xmlSource = DefaultUnmarshallers.StringUnmarshaller(content).right.get
xstream.fromXML(xmlSource).asInstanceOf[A]
}
}
}
}
implicit def sprayXmlJsonMarshaller[A: RootJsonWriter] = new SimpleMarshaller[A] {
val canMarshalTo = ContentType(`application/json`, `UTF-8`) :: ContentType(`text/xml`, `UTF-8`) :: Nil
private val printer = if (SprayBaseSettings.CompactJsonPrinting) CompactPrinter else PrettyPrinter
def marshal(value: A, contentType: ContentType) = {
contentType.mediaType match {
case MediaTypes.`application/json` => {
val json = value.toJson
val jsonSource = printer(json)
DefaultMarshallers.StringMarshaller.marshal(jsonSource, contentType)
}
case _ => {
val xml = xstream.toXML(value)
DefaultMarshallers.StringMarshaller.marshal(xml, contentType)
}
}
}
}
}
object SprayXmlJsonSupport extends SprayXmlJsonSupport
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment