Как я могу отправить массив объектов json в запросе akka-http - PullRequest
0 голосов
/ 11 июня 2019

Я могу обработать {"phone": "2312323", "message": "This is test"} в Akka-Http, используя

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 ]

1 голос
/ 11 июня 2019

Привет Вы можете сделать так:

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

0 голосов
/ 11 июня 2019

Вы можете использовать более простой способ, с меньшим количеством кода (и используйте 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)
                }
              }
              }
            }
...