Akka(34): Http葡京网上娱乐场:Unmarshalling,from Json

 
Unmarshalling是Akka-http内把网上可传输格式的多少转变成程序高级结构话数据的进程,比如把Json数据转换成某个自定义类型的实例。按实际流程来说就是先把Json转换成可传输格式数据如:MessageEntity,HttpRequest,HttpReponse等,然后再转换成程序高级结构数据如classXX实例。Unmarshalling对一个A类实例到B类实例的转移是因此Unmarshaller[A,B]来促成的:

 
Akka-http是一项系统融为一体工具。这首要借助系统里面的数据互换效率。因为程序内数据表明形式与网上传输的数码格式是不均等的,所以需要对程序高级结构化的数额举办转移(marshalling
or
serializing)成为可在网上传输的多少格式。由于可能波及到异类系统融为一体,网上传输数据格式是一个当着的规范,这样大家才都可以开展辨析。Json就是是一个脚下业界广泛接受的网上互换数据格式。当然,所谓的多少格式转换应该是双向的,还亟需包括把接受的网上传输数据转换成程序高级结构化数据。

trait Unmarshaller[-A, B] extends akka.http.javadsl.unmarshalling.Unmarshaller[A, B] {...}
object Unmarshaller
  extends GenericUnmarshallers
  with PredefinedFromEntityUnmarshallers
  with PredefinedFromStringUnmarshallers {

  // format: OFF

  //#unmarshaller-creation
  /**
   * Creates an `Unmarshaller` from the given function.
   */
  def apply[A, B](f: ExecutionContext ⇒ A ⇒ Future[B]): Unmarshaller[A, B] =
    withMaterializer(ec => _ => f(ec))
...}

Akka-http网上交流数据转换代表把一个尖端结构类型T的实例转换成简单的对象项目如MessageEntity,它表示http音讯中的数据部分(entity-body),最后爆发Json举办交换。Akka-http用马尔斯haller[A,B]品种来举行类型A的实例到花色B实例的变换。Marshaller[A,B]概念如下:

从Unmarshaller的构建函数apply可以估摸它的效果应该与函数A=>Future[B]很相像。A代表网上可传输类型如MessageEntity、HttpRequest,B代表某种程序高级数据类型。因为A到B的转移是non-blocking的,所以可以登时再次回到Future类型结果。Akka-http按被更换对象类型分类命名了上面这一个品种别名:

sealed abstract class Marshaller[-A, +B] {

  def apply(value: A)(implicit ec: ExecutionContext): Future[List[Marshalling[B]]]

  def map[C](f: B ⇒ C): Marshaller[A, C] =
    Marshaller(implicit ec ⇒ value ⇒ this(value).fast map (_ map (_ map f)))
...
}

//#marshaller-creation
object Marshaller
  extends GenericMarshallers
  with PredefinedToEntityMarshallers
  with PredefinedToResponseMarshallers
  with PredefinedToRequestMarshallers {

  /**
   * Creates a [[Marshaller]] from the given function.
   */
  def apply[A, B](f: ExecutionContext ⇒ A ⇒ Future[List[Marshalling[B]]]): Marshaller[A, B] =
    new Marshaller[A, B] {
      def apply(value: A)(implicit ec: ExecutionContext) =
        try f(ec)(value)
        catch { case NonFatal(e) ⇒ FastFuture.failed(e) }
    }
...
}
type FromEntityUnmarshaller[T] = Unmarshaller[HttpEntity, T]
type FromMessageUnmarshaller[T] = Unmarshaller[HttpMessage, T]
type FromResponseUnmarshaller[T] = Unmarshaller[HttpResponse, T]
type FromRequestUnmarshaller[T] = Unmarshaller[HttpRequest, T]
type FromByteStringUnmarshaller[T] = Unmarshaller[ByteString, T]
type FromStringUnmarshaller[T] = Unmarshaller[String, T]
type FromStrictFormFieldUnmarshaller[T] = Unmarshaller[StrictForm.Field, T]

构建函数apply[A,B]包嵌了个操作函数:A=>Future[List[Marshalling[B]]],至于缘何不采用更简便易行直接的措施A=>B是因为:

Akka-http对以下系列提供了机关的Unmarshalling转换: 

1、转换的长河是异步non-blocking的,所以回来Future[??]

PredefinedFromStringUnmarshallers
Byte
Short
Int
Long
Float
Double
Boolean
PredefinedFromEntityUnmarshallers
Array[Byte]
ByteString
Array[Char]
String
akka.http.scaladsl.model.FormData
GenericUnmarshallers
Unmarshaller[T, T] (identity unmarshaller)
Unmarshaller[Option[A], B], if an Unmarshaller[A, B] is available
Unmarshaller[A, Option[B]], if an Unmarshaller[A, B] is available

2、可能有多种转移目标数据格式如XML,Json:所以用List[??]表达

也就是说Akka-http提供了这多少个U类型的Unmarshaller[U,B]隐式实例。Akka-http也提供了工具类型Unmarshal:

3、假诺急需在发生最后目的格式数据前能取得或者修改数据的特性,就需要在数据源与对象数据里面设一个中档层结果,马尔斯(Mars)halling[B]就是如此一个中间抽象层类型。通过马尔斯halling类型可以在多少实际上暴发此前拿到或修改数据属性:

object Unmarshal {
  def apply[T](value: T): Unmarshal[T] = new Unmarshal(value)
}

class Unmarshal[A](val value: A) {
  /**
   * Unmarshals the value to the given Type using the in-scope Unmarshaller.
   *
   * Uses the default materializer [[ExecutionContext]] if no implicit execution context is provided.
   * If you expect the marshalling to be heavy, it is suggested to provide a specialized context for those operations.
   */
  def to[B](implicit um: Unmarshaller[A, B], ec: ExecutionContext = null, mat: Materializer): Future[B] = {
    val context: ExecutionContext = if (ec == null) mat.executionContext else ec

    um(value)(context, mat)
  }
}
/**
 * Describes one possible option for marshalling a given value.
 */
sealed trait Marshalling[+A] {
  def map[B](f: A ⇒ B): Marshalling[B]

  /**
   * Converts this marshalling to an opaque marshalling, i.e. a marshalling result that
   * does not take part in content type negotiation. The given charset is used if this
   * instance is a `WithOpenCharset` marshalling.
   */
  def toOpaque(charset: HttpCharset): Marshalling[A]
}

object Marshalling {

  /**
   * A Marshalling to a specific [[akka.http.scaladsl.model.ContentType]].
   */
  final case class WithFixedContentType[A](
    contentType: ContentType,
    marshal:     () ⇒ A) extends Marshalling[A] {
    def map[B](f: A ⇒ B): WithFixedContentType[B] = copy(marshal = () ⇒ f(marshal()))
    def toOpaque(charset: HttpCharset): Marshalling[A] = Opaque(marshal)
  }

  /**
   * A Marshalling to a specific [[akka.http.scaladsl.model.MediaType]] with a flexible charset.
   */
  final case class WithOpenCharset[A](
    mediaType: MediaType.WithOpenCharset,
    marshal:   HttpCharset ⇒ A) extends Marshalling[A] {
    def map[B](f: A ⇒ B): WithOpenCharset[B] = copy(marshal = cs ⇒ f(marshal(cs)))
    def toOpaque(charset: HttpCharset): Marshalling[A] = Opaque(() ⇒ marshal(charset))
  }

  /**
   * A Marshalling to an unknown MediaType and charset.
   * Circumvents content negotiation.
   */
  final case class Opaque[A](marshal: () ⇒ A) extends Marshalling[A] {
    def map[B](f: A ⇒ B): Opaque[B] = copy(marshal = () ⇒ f(marshal()))
    def toOpaque(charset: HttpCharset): Marshalling[A] = this
  }
}

俺们可以透过Unmarshal.to[B]把Unmarshal[A]转换成Future[B]。注意:这一步只包括了从网上可传输类型到程序类型转换这一过程,不包括实际实现时的Json转换。上面是局部Unmarshal的用例:

我们得以在马尔斯(Mars)halling类型里对信息内容类型(message-content-type)举办操作。为了便于操作,Akka-http提供了上面这一个档次别名:

import akka.actor._
import akka.stream._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._

object Unmarshalling {
  implicit val httpSys = ActorSystem("httpSystem")
  implicit val httpMat = ActorMaterializer()
  implicit val httpEC = httpSys.dispatcher

  val futInt = Unmarshal(43).to[Int]
  val futBoolean = Unmarshal("0").to[Boolean]
  val futString = Unmarshal(HttpEntity("Hello")).to[String]
  val futHello = Unmarshal(HttpRequest(method = HttpMethods.GET, entity = HttpEntity("hello")))

}
type ToEntityMarshaller[T] = Marshaller[T, MessageEntity]
type ToByteStringMarshaller[T] = Marshaller[T, ByteString]
type ToHeadersAndEntityMarshaller[T] = Marshaller[T, (immutable.Seq[HttpHeader], MessageEntity)]
type ToResponseMarshaller[T] = Marshaller[T, HttpResponse]
type ToRequestMarshaller[T] = Marshaller[T, HttpRequest]

如上都是已知类型之间转换,可能没什么实际用途,不像marshalling:中间层马尔斯halling有实际转换的需要。Unmarshalling可以直接举办Json到自定义类型之间的转移,如:

基本上是以目的数据类型来分类代表的。Akka-http提供了成百上千门类的预设实例到Mashalling转换:

 val route = (path("User") & post) { entity(as[User]){ user =>
    complete(Future(s"inserting user: $user"))
  }} ~
    (path("Item"/IntNumber) & put) { id => entity(as[Item]){ item =>
      complete(Future(s"update item $id: $item"))
    }}
PredefinedToEntityMarshallers
Array[Byte]
ByteString
Array[Char]
String
akka.http.scaladsl.model.FormData
akka.http.scaladsl.model.MessageEntity
T <: akka.http.scaladsl.model.Multipart
PredefinedToResponseMarshallers
T, if a ToEntityMarshaller[T] is available
HttpResponse
StatusCode
(StatusCode, T), if a ToEntityMarshaller[T] is available
(Int, T), if a ToEntityMarshaller[T] is available
(StatusCode, immutable.Seq[HttpHeader], T), if a ToEntityMarshaller[T] is available
(Int, immutable.Seq[HttpHeader], T), if a ToEntityMarshaller[T] is available
PredefinedToRequestMarshallers
HttpRequest
Uri
(HttpMethod, Uri, T), if a ToEntityMarshaller[T] is available
(HttpMethod, Uri, immutable.Seq[HttpHeader], T), if a ToEntityMarshaller[T] is available
GenericMarshallers
Marshaller[Throwable, T]
Marshaller[Option[A], B], if a Marshaller[A, B] and an EmptyValue[B] is available
Marshaller[Either[A1, A2], B], if a Marshaller[A1, B] and a Marshaller[A2, B] is available
Marshaller[Future[A], B], if a Marshaller[A, B] is available
Marshaller[Try[A], B], if a Marshaller[A, B] is available

如上是因此Directive
as[???]实现的:

Akka-http还提供了一个工具类马尔斯(Mars)hal:

 /**
   * Returns the in-scope [[FromRequestUnmarshaller]] for the given type.
   *
   * @group marshalling
   */
  def as[T](implicit um: FromRequestUnmarshaller[T]) = um
class Marshal[A](val value: A) {
  /**
   * Marshals `value` using the first available [[Marshalling]] for `A` and `B` provided by the given [[Marshaller]].
   * If the marshalling is flexible with regard to the used charset `UTF-8` is chosen.
   */
  def to[B](implicit m: Marshaller[A, B], ec: ExecutionContext): Future[B] =
    m(value).fast.map {
      _.head match {
        case Marshalling.WithFixedContentType(_, marshal) ⇒ marshal()
        case Marshalling.WithOpenCharset(_, marshal)      ⇒ marshal(HttpCharsets.`UTF-8`)
        case Marshalling.Opaque(marshal)                  ⇒ marshal()
      }
    }

  /**
   * Marshals `value` to an `HttpResponse` for the given `HttpRequest` with full content-negotiation.
   */
  def toResponseFor(request: HttpRequest)(implicit m: ToResponseMarshaller[A], ec: ExecutionContext): Future[HttpResponse] = {
    import akka.http.scaladsl.marshalling.Marshal._
    val ctn = ContentNegotiator(request.headers)

    m(value).fast.map { marshallings ⇒
      val supportedAlternatives: List[ContentNegotiator.Alternative] =
        marshallings.collect {
          case Marshalling.WithFixedContentType(ct, _) ⇒ ContentNegotiator.Alternative(ct)
          case Marshalling.WithOpenCharset(mt, _)      ⇒ ContentNegotiator.Alternative(mt)
        }(collection.breakOut)
      val bestMarshal = {
        if (supportedAlternatives.nonEmpty) {
          ctn.pickContentType(supportedAlternatives).flatMap {
            case best @ (_: ContentType.Binary | _: ContentType.WithFixedCharset | _: ContentType.WithMissingCharset) ⇒
              marshallings collectFirst { case Marshalling.WithFixedContentType(`best`, marshal) ⇒ marshal }
            case best @ ContentType.WithCharset(bestMT, bestCS) ⇒
              marshallings collectFirst {
                case Marshalling.WithFixedContentType(`best`, marshal) ⇒ marshal
                case Marshalling.WithOpenCharset(`bestMT`, marshal)    ⇒ () ⇒ marshal(bestCS)
              }
          }
        } else None
      } orElse {
        marshallings collectFirst { case Marshalling.Opaque(marshal) ⇒ marshal }
      } getOrElse {
        throw UnacceptableResponseContentTypeException(supportedAlternatives.toSet)
      }
      bestMarshal()
    }
  }
}

这亟需把FromRequestUmarshaller[T]座落可视域内,FromRequestUmarshaller[T]实际是Unmarshaller[T,B]的别名: 

咱俩得以用马尔斯hal.to和toResponseFor(request)把Akka-http提供的预设可转换类实例转换成相关的toResponse马尔斯hallable类实例。因为Server-Directive如complete接受一个toResponse马尔斯hallable来构建HttpResponse:

type FromRequestUnmarshaller[T] = Unmarshaller[HttpRequest, T]
  /**
   * Completes the request using the given arguments.
   *
   * @group route
   */
  def complete(m: ⇒ ToResponseMarshallable): StandardRoute =
    StandardRoute(_.complete(m))

在上篇研究大家介绍了Akka-http的马尔斯(Mars)halling是type-class形式的。其中紧要可以参照上篇钻探。现在我们需要那些Unmarshaller的隐式实例:

在另一个目标里提供了ToResponse马尔斯(Mars)hallable隐式转换:

trait Formats extends SprayJsonSupport with DefaultJsonProtocol
object Converters extends Formats {
  case class User(id: Int, name: String)
  case class Item(id: Int, name: String, price: Double)
  implicit val itemFormat = jsonFormat3(Item.apply)
  implicit val userFormat = jsonFormat2(User.apply)
}

object Unmarshalling {
  import Converters._
...
/** Something that can later be marshalled into a response */
trait ToResponseMarshallable {
  type T
  def value: T
  implicit def marshaller: ToResponseMarshaller[T]

  def apply(request: HttpRequest)(implicit ec: ExecutionContext): Future[HttpResponse] =
    Marshal(value).toResponseFor(request)
}

object ToResponseMarshallable {
  implicit def apply[A](_value: A)(implicit _marshaller: ToResponseMarshaller[A]): ToResponseMarshallable =
    new ToResponseMarshallable {
      type T = A
      def value: T = _value
      def marshaller: ToResponseMarshaller[T] = _marshaller
    }

  implicit val marshaller: ToResponseMarshaller[ToResponseMarshallable] =
    Marshaller { implicit ec ⇒ marshallable ⇒ marshallable.marshaller(marshallable.value) }
}

万一采纳Json4s的实现形式,大家需要如下提供那些隐式实例:

若果在可视域内(implicit
scope)能发现马尔斯(Mars)haller[A,B]的隐式实例就能满意complete入参要求了。上边是一对马尔斯hal用例:

trait JsonCodec extends Json4sSupport {
  import org.json4s.DefaultFormats
  import org.json4s.ext.JodaTimeSerializers
  implicit val serilizer = jackson.Serialization
  implicit val formats = DefaultFormats ++ JodaTimeSerializers.all
}
object JsConverters extends JsonCodec
import akka.util.ByteString
import akka.http.scaladsl.model.{HttpResponse, MessageEntity}
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._

object Marshalling  {

  val string = "Yeah"
  val entityFuture = Marshal(string).to[MessageEntity]
  val errorMsg = "Easy, pal!"
  val responseFuture = Marshal(420 -> errorMsg).to[HttpResponse]
  val request = HttpRequest(headers = List(headers.Accept(MediaTypes.`application/json`)))
  val responseText = "Plaintext"
  val respFuture = Marshal(responseText).toResponseFor(request) // with content negotiation!
  val bsFuture = Marshal("oh my!").to[ByteString]
  val reqFuture = Marshal("can you?").to[HttpRequest]
  val resp = reqFuture.flatMap {r => Marshal("ok").toResponseFor(r)}

}

Json4s的有血有肉用例如下:

这就是说对于那么些自定义的类型U,由于不容许有预设定对应的马尔斯haller[U,B],应该如何是好?如简单的case
class:

  import scala.collection.mutable._
  case class User(id: Int, name: String)
  class Item(id: Int, name: String, price: Double)
  object AnyPic {
    val area = 10
    val title = "a picture"
    val data = ArrayBuffer[Byte](1,2,3)
  }

  val route = (path("User") & post) { entity(as[User]){ user =>
    complete(Future(s"inserting user: $user"))
  }} ~
    (path("Item"/IntNumber) & put) { id => entity(as[Item]){ item =>
      complete(Future(s"update item $id: $item"))
    }} ~
    (path("Picture") & put) { entity(as[AnyPic.type]){ pic =>
      complete(Future(s"insert picture: $pic"))
    }}
  case class User(id: Int, name: String)
  case class Item(id: Int, name: String, price: Double)
  val john = Marshal(User(1,"John")).to[MessageEntity]
  val fruit = Marshal(Item(1,"banana", 3.5)).to[MessageEntity]

  val route =
    get {
      path("items") {
        complete(fruit)
      } ~
      path("users") {
        complete(john)
      }
    }

从效率上和发挥灵活性来讲,Json4s的落实情势要占优。

总的看把User,Item类型实例转成ToResponse马尔斯hallable是从来不问题的。可是,通过隐式转换ToResponse马尔斯(Mars)hallable被转换成马尔斯(Mars)haller[U,B],而实例化这多少个类此外长河即构建网上传输格式的数额时需要更多的支撑。这些可网上传输的信息是透过Json、XML这样的多寡描述语言来暴发实际多少的。Akka-http通过akka-http-spray-json模块直接协理由Spray-Json实现的Json读写工具库。具体Json读写是经过RootJsonFormat[T]用作接口实现的:

上面就是此次商量的示范源代码:

/**
 * A special JsonFormat signaling that the format produces a legal JSON root object, i.e. either a JSON array
 * or a JSON object.
 */
trait RootJsonFormat[T] extends JsonFormat[T] with RootJsonReader[T] with RootJsonWriter[T]

RootJsonFormat[T]代表T类型实例的Json转换。RootJsonFormat[T]的继承父辈包括:
/**
  * Provides the JSON deserialization and serialization for type T.
 */
trait JsonFormat[T] extends JsonReader[T] with JsonWriter[T]

/**
 * A special JsonReader capable of reading a legal JSON root object, i.e. either a JSON array or a JSON object.
 */
@implicitNotFound(msg = "Cannot find RootJsonReader or RootJsonFormat type class for ${T}")
trait RootJsonReader[T] extends JsonReader[T]

/**
 * A special JsonWriter capable of writing a legal JSON root object, i.e. either a JSON array or a JSON object.
 */
@implicitNotFound(msg = "Cannot find RootJsonWriter or RootJsonFormat type class for ${T}")
trait RootJsonWriter[T] extends JsonWriter[T]

Unmarshalling

它们又持续了现实的Json读写工具类:

import akka.actor._
import akka.stream._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import scala.concurrent._
import akka.http.scaladsl.marshallers.sprayjson._
import spray.json._

trait Formats extends SprayJsonSupport with DefaultJsonProtocol
object Converters extends Formats {
  case class User(id: Int, name: String)
  case class Item(id: Int, name: String, price: Double)
  implicit val itemFormat = jsonFormat3(Item.apply)
  implicit val userFormat = jsonFormat2(User.apply)
}

object Unmarshalling {
  import Converters._
  implicit val httpSys = ActorSystem("httpSystem")
  implicit val httpMat = ActorMaterializer()
  implicit val httpEC = httpSys.dispatcher

  val futInt = Unmarshal(43).to[Int]
  val futBoolean = Unmarshal("0").to[Boolean]
  val futString = Unmarshal(HttpEntity("Hello")).to[String]
  val futHello = Unmarshal(HttpRequest(method = HttpMethods.GET, entity = HttpEntity("hello")))

  val route = (path("User") & post) { entity(as[User]){ user =>
    complete(Future(s"inserting user: $user"))
  }} ~
    (path("Item"/IntNumber) & put) { id => entity(as[Item]){ item =>
      complete(Future(s"update item $id: $item"))
    }}

}
/**
  * Provides the JSON deserialization for type T.
 */
@implicitNotFound(msg = "Cannot find JsonReader or JsonFormat type class for ${T}")
trait JsonReader[T] {
  def read(json: JsValue): T
}

object JsonReader {
  implicit def func2Reader[T](f: JsValue => T): JsonReader[T] = new JsonReader[T] {
    def read(json: JsValue) = f(json)
  }
}

/**
  * Provides the JSON serialization for type T.
 */
@implicitNotFound(msg = "Cannot find JsonWriter or JsonFormat type class for ${T}")
trait JsonWriter[T] {
  def write(obj: T): JsValue
}

object JsonWriter {
  implicit def func2Writer[T](f: T => JsValue): JsonWriter[T] = new JsonWriter[T] {
    def write(obj: T) = f(obj)
  }
}

Json4sUnmarshalling

它们提供了函数JsValue=>T到Json里德(Reade)r[T]及T=>JsValue到JsonWriter直接的隐式转换。Akka-http的Json解决方案是卓绝的type-class情势:是一种可以轻易创设效率的项目继承格局(add-hoc
polymorphism)。它的特性就是在可视域内(implicit
scope)应不同效能要求提供不同的功能实现项目标隐式实例(implicit
instance)。具体用例如下:

import akka.actor._
import akka.stream._
import akka.http.scaladsl.server.Directives._
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.jackson
import scala.concurrent._
trait JsonCodec extends Json4sSupport {
  import org.json4s.DefaultFormats
  import org.json4s.ext.JodaTimeSerializers
  implicit val serilizer = jackson.Serialization
  implicit val formats = DefaultFormats ++ JodaTimeSerializers.all
}
object JsConverters extends JsonCodec


object Json4sUnmarshalling {
  import JsConverters._
  implicit val httpSys = ActorSystem("httpSystem")
  implicit val httpMat = ActorMaterializer()
  implicit val httpEC = httpSys.dispatcher

  import scala.collection.mutable._
  case class User(id: Int, name: String)
  class Item(id: Int, name: String, price: Double)
  object AnyPic {
    val area = 10
    val title = "a picture"
    val data = ArrayBuffer[Byte](1,2,3)
  }

  val route = (path("User") & post) { entity(as[User]){ user =>
    complete(Future(s"inserting user: $user"))
  }} ~
    (path("Item"/IntNumber) & put) { id => entity(as[Item]){ item =>
      complete(Future(s"update item $id: $item"))
    }} ~
    (path("Picture") & put) { entity(as[AnyPic.type]){ pic =>
      complete(Future(s"insert picture: $pic"))
    }}
}
trait Formats extends SprayJsonSupport with DefaultJsonProtocol
object Converters extends Formats {
  case class User(id: Int, name: String)
  case class Item(id: Int, name: String, price: Double)
  implicit val itemFormat = jsonFormat3(Item.apply)
  implicit val userFormat = jsonFormat2(User.apply)
}

 

jsonFormatXX是Spray-Json提供的Json读写实现。大家把这些隐式实例置于当前可视域内即成功了与Akka-http的连片。我们来探视JsonFormat的定义:

 

trait ProductFormatsInstances { self: ProductFormats with StandardFormats =>
  // Case classes with 1 parameters

  def jsonFormat1[P1 :JF, T <: Product :ClassManifest](construct: (P1) => T): RootJsonFormat[T] = {
    val Array(p1) = extractFieldNames(classManifest[T])
    jsonFormat(construct, p1)
  }
  def jsonFormat[P1 :JF, T <: Product](construct: (P1) => T, fieldName1: String): RootJsonFormat[T] = new RootJsonFormat[T]{
    def write(p: T) = {
      val fields = new collection.mutable.ListBuffer[(String, JsValue)]
      fields.sizeHint(1 * 2)
      fields ++= productElement2Field[P1](fieldName1, p, 0)
      JsObject(fields: _*)
    }
    def read(value: JsValue) = {
      val p1V = fromField[P1](value, fieldName1)
      construct(p1V)
    }
  }
...
}

 

我们来看了jsonFormat重返结果类型是RootJsonFormat[T]。假诺有个case
class T,通过jsonFormat可以拿到read(value:
JsValue)及write(p:T)这几个实际的Json读写函数。Spray-Json提供的预设了Json转换的花色包括下边各样别:

 

/**
  * Provides all the predefined JsonFormats.
 */
trait DefaultJsonProtocol
        extends BasicFormats
        with StandardFormats
        with CollectionFormats
        with ProductFormats
        with AdditionalFormats

object DefaultJsonProtocol extends DefaultJsonProtocol

 

例如BasicFormat:

 

/**
  * Provides the JsonFormats for the most important Scala types.
 */
trait BasicFormats {

  implicit object IntJsonFormat extends JsonFormat[Int] {
    def write(x: Int) = JsNumber(x)
    def read(value: JsValue) = value match {
      case JsNumber(x) => x.intValue
      case x => deserializationError("Expected Int as JsNumber, but got " + x)
    }
  }
...
}

 

这么些项目的Json转换已经是具体的read/write操作了。在SprayJsonSupport
trait里有最后的马尔斯(Mars)haller[U,B]链接:

 

/**
 * A trait providing automatic to and from JSON marshalling/unmarshalling using an in-scope *spray-json* protocol.
 */
trait SprayJsonSupport {
...
  implicit def sprayJsonUnmarshaller[T](implicit reader: RootJsonReader[T]): FromEntityUnmarshaller[T] =
    sprayJsValueUnmarshaller.map(jsonReader[T].read)
...
  //#sprayJsonMarshallerConverter
  implicit def sprayJsonMarshaller[T](implicit writer: RootJsonWriter[T], printer: JsonPrinter = CompactPrinter): ToEntityMarshaller[T] =
    sprayJsValueMarshaller compose writer.write
...
}

 

我们在上头提到过FromEntityUnmarshaller[T]和ToEntityMarshaller[T]的是Marshaller[A,B]的别名:

 

  type FromEntityUnmarshaller[T] = Unmarshaller[HttpEntity, T]

  type ToEntityMarshaller[T] = Marshaller[T, MessageEntity]

 

既然Akka-http的Json实现模式是type-class格局的,那么我们就摸索此外Json库的意义实现格局,如:Json4s。大家需要在build.sbt中进入下边的依靠:

 

  "de.heikoseeberger" %% "akka-http-json4s" % "1.19.0-M2",
  "org.json4s" %% "json4s-jackson" % "3.6.0-M1",
  "org.json4s" %% "json4s-ext" % "3.6.0-M1",

 

 akka-http-Json4s通过trait
Json4sSupport提供了Json4s实现格局:

 

trait Json4sSupport {
...
  /**
    * HTTP entity => `A`
    *
    * @tparam A type to decode
    * @return unmarshaller for `A`
    */
  implicit def unmarshaller[A: Manifest](implicit serialization: Serialization,
                                         formats: Formats): FromEntityUnmarshaller[A] = ...

  /**
    * `A` => HTTP entity
    *
    * @tparam A type to encode, must be upper bounded by `AnyRef`
    * @return marshaller for any `A` value
    */
  implicit def marshaller[A <: AnyRef](implicit serialization: Serialization,
                                       formats: Formats,
                                       shouldWritePretty: ShouldWritePretty =
                                         ShouldWritePretty.False): ToEntityMarshaller[A] = ...

 

平等提供了FromEntityUn马尔斯(Mars)haller[A]和ToEntityMarshaller[A]这两类的隐式实例。Serialization提供了Json的切切实实读写函数:

 

trait Serialization {
  import java.io.{Reader, Writer}
  /** Serialize to String.
   */
  def write[A <: AnyRef](a: A)(implicit formats: Formats): String
...
  /** Deserialize from a String.
   */
  def read[A](json: String)(implicit formats: Formats, mf: Manifest[A]): A = read(StringInput(json))
...
}

 

Formats就是Json4s提供的享有Json转换预设类:

 

trait Formats extends Serializable { self: Formats =>
...
  def withBigInt: Formats = copy(wWantsBigInt = true)

  def withLong: Formats = copy(wWantsBigInt = false)

  def withBigDecimal: Formats = copy(wWantsBigDecimal = true)

...
}

 

看起来我们只需在可视域内提供Serialization和Formats类型的隐式实例就行了:

 

import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.jackson
trait JsonCodec extends Json4sSupport {
  import org.json4s.DefaultFormats
  import org.json4s.ext.JodaTimeSerializers
  implicit val serilizer = jackson.Serialization
  implicit val formats = DefaultFormats ++ JodaTimeSerializers.all
}
object JsConverters extends JsonCodec

 

看望实际用例:

  import scala.collection.mutable._
  case class User(id: Int, name: String)
  class Item(id: Int, name: String, price: Double)
  object AnyPic {
    val area = 10
    val title = "a picture"
    val data = ArrayBuffer[Byte](1,2,3)
  }

  val john = Marshal(User(1,"John")).to[MessageEntity]
  val fruit = Marshal(new Item(1,"banana", 3.5)).to[MessageEntity]
  val pic = Marshal(AnyPic).to[MessageEntity]

非但省却了再一次的JsonFormatXX,而且意义更加灵活有力:因为不再局限于case
class这一种自定义类型了,在无需额外代码情形下class,object等成套都辅助。

下面是本篇探讨示范的源代码:

build.sbt

name := "learn-http"

version := "0.1"

scalaVersion := "2.12.3"

libraryDependencies ++= Seq(
  "de.heikoseeberger" %% "akka-http-json4s" % "1.19.0-M2",
  "org.json4s" %% "json4s-jackson" % "3.6.0-M1",
  "org.json4s" %% "json4s-ext" % "3.6.0-M1",
  "com.typesafe.akka" %% "akka-http" % "10.0.10",
  "com.typesafe.akka" %% "akka-actor" % "2.5.4",
  "com.typesafe.akka" %% "akka-stream" % "2.5.4",
  "com.typesafe.akka" %% "akka-http-spray-json" % "10.0.10"
)

Marshalling

import akka.actor._
import akka.stream._
import akka.util.ByteString
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.marshallers.sprayjson._
import spray.json._

trait Formats extends SprayJsonSupport with DefaultJsonProtocol
object Converters extends Formats {
  case class User(id: Int, name: String)
  case class Item(id: Int, name: String, price: Double)
  implicit val itemFormat = jsonFormat3(Item.apply)
  implicit val userFormat = jsonFormat2(User.apply)
}


object Marshalling {
  import Converters._
  implicit val httpSys = ActorSystem("httpSystem")
  implicit val httpMat = ActorMaterializer()
  implicit val httpEC = httpSys.dispatcher



  val string = "Yeah"
  val entityFuture = Marshal(string).to[MessageEntity]
  val errorMsg = "Easy, pal!"
  val responseFuture = Marshal(420 -> errorMsg).to[HttpResponse]
  val request = HttpRequest(headers = List(headers.Accept(MediaTypes.`application/json`)))
  val responseText = "Plaintext"
  val respFuture = Marshal(responseText).toResponseFor(request)

//  val bsFuture = Marshal("oh my!").to[ByteString]
  //  val reqFuture = Marshal(400).to[HttpRequest]
  //  val resp = reqFuture.flatMap {r => Marshal("ok").toResponseFor(r)}


  val john = Marshal(User(1,"John")).to[MessageEntity]
  val fruit = Marshal(Item(1,"banana", 3.5)).to[MessageEntity]

  val route =
    get {
      path("items") {
        complete(fruit)
      } ~
        path("users") {
          complete(john)
        }
    }

}

 Json4sMarshalling

import akka.actor._
import akka.stream._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.jackson
trait JsonCodec extends Json4sSupport {
  import org.json4s.DefaultFormats
  import org.json4s.ext.JodaTimeSerializers
  implicit val serilizer = jackson.Serialization
  implicit val formats = DefaultFormats ++ JodaTimeSerializers.all
}
object JsConverters extends JsonCodec


object Json4sMarshalling {
  import JsConverters._
  implicit val httpSys = ActorSystem("httpSystem")
  implicit val httpMat = ActorMaterializer()
  implicit val httpEC = httpSys.dispatcher

  val string = "Yeah"
  val entityFuture = Marshal(string).to[MessageEntity]
  val errorMsg = "Easy, pal!"
  val responseFuture = Marshal(420 -> errorMsg).to[HttpResponse]
  val request = HttpRequest(headers = List(headers.Accept(MediaTypes.`application/json`)))
  val responseText = "Plaintext"
  val respFuture = Marshal(responseText).toResponseFor(request)




  import scala.collection.mutable._
  case class User(id: Int, name: String)
  class Item(id: Int, name: String, price: Double)
  object AnyPic {
    val area = 10
    val title = "a picture"
    val data = ArrayBuffer[Byte](1,2,3)
  }

  val john = Marshal(User(1,"John")).to[MessageEntity]
  val fruit = Marshal(new Item(1,"banana", 3.5)).to[MessageEntity]
  val pic = Marshal(AnyPic).to[MessageEntity]

  val route =
    get {
      path("items") {
        complete(fruit)
      } ~
        path("users") {
          complete(john)
        } ~
      path("pic") {
        complete(pic)
      }
    }

}