New to akka-http

173 views Asked by At

I am new to akka-http. I am using this in my project. I am not able to understand what exactly marshalling and unmarshalling is.

If someone can explain it with a brief example showing how to marshall and unmarshall json.

1

There are 1 answers

1
mhashim On

When you receive a request the in http it is in wire format i.e byte string, Unmarshaling is converting this byte string to higher level format, on the flip side is marshaling were you convert to low level format.

Example in akka-http of converting json string(str) to case class(person):

case class Person(name: String, age: Int)
val str = """{"name": "some", "aga": 10}"""
impicit val jsonF = jsonFormat2(Person)
val person = JsonParser(str).convertTo[Person]

But a better approach is using the entity directive from akka-http:

val route = post {
       entity(as[Person]) { person =>
       complete(s"Person: ${person.name} - favorite number:  ${person.favoriteNumber}")
  }
}

The example from the documentation here by the way you need the implicit formater in your scope for unmarshaling to succeed and the number to match the number of field in your case class.