如何在akka-http请求中发送json对象数组

时间:2019-06-11 03:00:49

标签: scala akka-http

我可以使用Akka-Http处理{"phone": "2312323", "message": "This is test"}

entity(as[Message]) { message =>
                  val f: Future[Any] = service ask message
                  onSuccess(f) { r: Any =>
                  {
                    r match {
                      case Some(message: Message) =>
                        complete(HttpEntity(ContentTypes.`application/json`, message.toJson.prettyPrint))
                      case _ =>
                        complete(StatusCodes.NotFound)
                    }
                  }
                  }
                }

但是我该怎么处理

[
     {"phone": "2312323", "message": "This is test"},
     {"phone": "2312321213", "message": "This is test 1212"}
]

2 个答案:

答案 0 :(得分:1)

嗨,你可以这样:

import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json._

// domain model
final case class Info(phone: String, message: String)
final case class MessageInfo(messages: List[Info])

// collect your json format instances into a support trait:
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val itemFormat = jsonFormat2(Info)
  implicit val orderFormat = jsonFormat1(MessageInfo) // contains List[Info]
}

// use it wherever json (un)marshalling is needed
class MyJsonService extends Directives with JsonSupport {

  // format: OFF
  val route =
    post {
      entity(as[MessageInfo]) { messageInfo => // will unmarshal JSON to Order
        val messageCount = messageInfo.messages.size
        val phoneNumbers = messageInfo.items.map(_.phone).mkString(", ")
        complete(s"Messages $messageCount with the contact number: $phoneNumbers")
      }
    }
  // format: ON
}

有关更多信息,请参见此处: https://doc.akka.io/docs/akka-http/current/common/json-support.html

答案 1 :(得分:0)

您可以使用一种更简单的方法,使用更少的代码(并使用gson):

val gson = new Gson
...

entity(as[String]) { messageStr =>
              val f: Future[Any] = service ask message
              onSuccess(f) { r: Any =>
              {
                r match {
                  case Some(messageStringValue: String) =>
                    val messagesList = gson.fromJson(messageStringValue, classOf[Array[Message]])
                    val messageCount = messagesList.size
                    val phoneNumbers = messagesList.map(_.phone).mkString(", ")
    complete(s"Messages $messageCount with the contact number: $phoneNumbers")
                  case _ =>
                    complete(StatusCodes.NotFound)
                }
              }
              }
            }