Implicit FromRequestUnmarsharell not found

I am trying to use my domain objects as parameters of a request / response body. I use spray and as[T]to unleash an object. But constantly I get could not find implicit value for parameter um: spray.httpx.unmarshalling.FromRequestUnmarshaller. Despite the fact that I added a hidden unmarshaller manually for the companion object, I get the same error. I have no idea what is wrong. This JSON serializer / deserializer is for the event that I wrote because I need to serialize a joda DateTime object.

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)
}
+4
source share
1 answer

Ok, I figured it out. The order of the structures is incorrect. First there must be a companion object and a second sign with a route. I don’t know why, but it works now.

+2

Source: https://habr.com/ru/post/1541040/


All Articles