Reputation: 915
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"}
]
Upvotes: 1
Views: 690
Reputation: 2397
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)
}
}
}
}
Upvotes: 0
Reputation: 1180
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
Upvotes: 1