让我们从一段代码开始:
val authData = AuthenticationData("user", "password", None)
val marshalledData: Future[ResponseEntity] = Marshal(authData).to[MessageEntity]
val unmarshalledData: Future[AuthenticationData] = marshalledData.flatMap((data: MessageEntity) =>
Unmarshal(data).to[AuthenticationData])
编组按预期工作。有转换为json的导入含义:
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json._
import com.onix.messages.JsonProtocolReadWrite._
由于某种原因,解组不起作用:
MarshallerTest.scala:22: could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.Unmarshaller[akka.http.scaladsl.model.MessageEntity,com.adform.dco.onix.messages.AuthenticationData]
[error] Unmarshal(data).to[AuthenticationData]}
RootJsonFormat[AuthenticationData]
在JsonProtocolReadWrite
下实施,因此可在范围内使用。
修改
JsonProtocolReadWrite
object JsonProtocolReadWrite extends DefaultJsonProtocol {
implicit object AuthDataFormat extends RootJsonFormat[AuthenticationData] {
def write(c: AuthenticationData) = {
val ip: JsValue = c.ipAddress.map(JsString(_)).getOrElse(JsNull)
JsObject(
"Username" -> JsString(c.userName),
"Password" -> JsString(c.password),
"ClientIp" -> ip
)
}
def read(value: JsValue): AuthenticationData = value.asJsObject.getFields("Username", "Password", "ClientIp") match {
case Seq(JsString(user), JsString(password), JsString(ip)) => AuthenticationData(user, password, Some(ip))
case Seq(JsString(user), JsString(password), JsNull) => AuthenticationData(user, password, None)
case _ => deserializationError("AuthenticationData object expected")
}
}
}