To automatically convert between domain models and JSON using Akka HTTP’s marshalling capabilities, follow these steps:
1. Add necessary dependencies : Include “akka-http-spray-json” and “spray-json” in your build configuration.
2. Import required packages : Import “akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport” and “spray.json.DefaultJsonProtocol”.
3. Define case classes : Create case classes representing your domain model.
4. Implement JsonFormat instances : Extend “DefaultJsonProtocol” and define implicit values for each case class using “jsonFormatX” methods, where X is the number of fields in the case class.
5. Mixin SprayJsonSupport : In the route definition or marshaller/unmarshaller scope, mixin “SprayJsonSupport” to enable automatic conversion.
6. Use directives : Utilize “entity(as[T])” directive for unmarshalling (JSON to domain model) and “complete()” directive with a case class instance for marshalling (domain model to JSON).
Example :
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
case class User(name: String, age: Int)
object UserJsonProtocol extends DefaultJsonProtocol {
implicit val userFormat = jsonFormat2(User)
}
import UserJsonProtocol._
val route =
path("users") {
post {
entity(as[User]) { user =>
complete(user)
}
}
}?