Play Framework自定义Unmarshaller与自定义媒体类型

时间:2016-02-18 10:59:40

标签: json scala playframework unmarshalling media-type

我有一个自定义JSON媒体类型,如:application/vnd.custom+json。我写了读者和作家或更好地说我的MyCustomObj

格式化

我想为此内容类型编写marshaller和unmarshaller。我在marshaller中取得了成功,但没有让unmarshaller为Play工作! JSON支持。代码段:

val `application/vnd.custom+json` = MediaTypes.register(MediaType.custom("application/vnd.custom+json"))

trait PlayMyCustomSupport extends PlayMyCustomFormat with PlayJsonSupport {
  implicit val playMyCustomMarshaller =
    Marshaller.delegate[MyCustomObj, JsValue](`application/vnd.custom+json`)(Json.toJson(_))

  // This ".asOpt.get" is just a hack to test if it works. Will implement later properly.
  implicit val playMyCustomUnmarshaller =
    Unmarshaller.delegate[JsValue, MyCustom](`application/vnd.custom+json`)(Json.fromJson[MyCustomObj](_).asOpt.get)
}

我的测试看起来像:

"allow unmarshalling a Json to a my custom object" in {
  val myCustomObj = MyCustomObj("foobar")
  val httpEntity = HttpEntity(`application/vnd.custom+json`, """{"custom":"foobar"}""")
  assert(httpEntity.as[MyCustomObj] === Right(myCustomObj))
}

当我运行测试时,我得到如下错误:

[info] - allow unmarshalling a Json to a my custom object *** FAILED ***
[info]   Left(UnsupportedContentType(Expected 'application/json')) did not equal Right(MyCustomObj(foobar))

所以某种方式我的自定义媒体类型没有注册或什么?奇怪的是,上面的编组工作正常。

谢谢!

最佳

0 个答案:

没有答案