简体   繁体   中英

How can I send array of json objects in akka-http request

I can handle {"phone": "2312323", "message": "This is test"} in Akka-Http using

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)
                    }
                  }
                  }
                }

but how can I handle

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

Hi You can do like this:

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
}

For more info please see here: https://doc.akka.io/docs/akka-http/current/common/json-support.html

You can use a simpler way, with less code (and use 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)
                }
              }
              }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM