Created
July 9, 2012 17:11
-
-
Save analytically/3077691 to your computer and use it in GitHub Desktop.
Spray XStream marshalling support
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
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