如何使用spray-json库将json应用于case类的实例

时间:2015-01-05 22:02:05

标签: scala akka spray-json

Registration.scala

package model

import akka.actor.Actor
import spray.json._
import DefaultJsonProtocol._

case class Registration(
  system: String, 
  identity: String)

object RegistrationProtocol extends DefaultJsonProtocol {
  implicit val adsRegistrationFormat = jsonFormat2(Registration)
}

RegistrationService.scala

import akka.actor.{Props, ActorLogging, Actor}
import model.Registration

object RegistrationsService {
  case class PostRegistrationMessage(registration: Registration)

  def props(property: String) = Props(classOf[RegistrationsService], property)
}

class RegistrationsService(property: String) extends Actor with ActorLogging {
  import RegistrationsService._

  def receive = {
    case PostRegistrationMessage(registration) => {
      import model.RegistrationProtocol._

      val json = registration.toJson

    }
  }
}

任何人都可以帮助我理解为什么这会因编译错误而失败"值toJson不是model.Registration"以及如何解决它。如果在上面代码的最后一行失败,那就是" val json = registration.toJson "

1 个答案:

答案 0 :(得分:5)

您还需要在RegistrationService.scala中导入由spray提供的隐式操作

  import model.RegistrationProtocol._
  import spray.json._