未找到隐式FromRequestUnmarsharell

时间:2014-05-18 18:29:38

标签: scala spray spray-json

我正在尝试将我的域对象用作请求/响应正文参数。我正在使用spray-routing和as[T]解组对象。但我一直在could not find implicit value for parameter um: spray.httpx.unmarshalling.FromRequestUnmarshaller。虽然我已经手动向对象对象添加了隐式unmarshaller,但我得到了相同的错误。我不知道出了什么问题。这个事件I的JSON序列化器/反序列化器已经编写,因为我需要序列化joda DateTime对象。

package services

import spray.routing.HttpService
import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormatter, ISODateTimeFormat}
import spray.httpx.unmarshalling.FromRequestUnmarshaller
import spray.json._
import services.EventsService.Event
import spray.httpx.SprayJsonSupport

trait EventsService extends HttpService {

  val eventsRoute =
    path("/events") {
      get {
        import EventsService._
        entity(as[Event]) { event =>
          complete(s"${event.toString}")
        }
      }
    }
}

object EventsService extends DefaultJsonProtocol with SprayJsonSupport{
  trait DateFormatter {
    val formatter: DateTimeFormatter
  }

  trait DateParser {
    val parser: DateTimeFormatter
  }

  implicit object EventFormatter extends RootJsonFormat[Event] with DateFormatter with DateParser {
    def read(json: JsValue): Event = json match {
      case obj: JsObject =>
        val name = obj.fields.get("name").map(_.asInstanceOf[JsString].value).
          getOrElse(deserializationError("field name not present"))
        val city = obj.fields.get("city").map(_.asInstanceOf[JsString].value).
          getOrElse(deserializationError("field city not present"))
        val starts = obj.fields.get("starts").map(x => parser.parseDateTime(x.asInstanceOf[JsString].value)).
          getOrElse(deserializationError("field starts not present"))
        val ends = obj.fields.get("ends").map(x => parser.parseDateTime(x.asInstanceOf[JsString].value)).
          getOrElse(deserializationError("ends field not present"))
        Event(name, city, starts, ends)
      case _ => deserializationError("wrong object to deserialize")
    }

    def write(e: Event): JsValue =
      JsObject(Map(
        "name" -> JsString(e.name),
        "city" -> JsString(e.city),
        "starts" -> JsString(formatter.print(e.starts)),
        "ends" -> JsString(formatter.print(e.ends))
      ))

    val formatter = ISODateTimeFormat.dateTimeNoMillis()
    val parser = ISODateTimeFormat.dateTimeNoMillis().withOffsetParsed()
  }

  case class Event(name: String, city: String, starts: DateTime, ends: DateTime)
}

1 个答案:

答案 0 :(得分:2)

好的,我已经明白了。结构的顺序是错误的。首先应该是伴侣对象和第二个具有路线的特征。我不知道为什么,但它现在有效。