Akka http with json4s

Akka Http uses the spray-json library for JSON support. But a few days back while working on a project which was using the json4s library for marshalling/unmarshalling, I got stuck during parsing of JSON request and extracting that parsed values into my target Scala data model.

Common transformations are summarized in the following picture.

Akka Http

Description :

  • I have a sample Scala web service created using Akka HTTP for performing CRUD operations which is not using any database for the time being as this blog focuses on json4s and Akka HTTP.
  • The user input contains objects which I want to extract cleanly. To keep things simpler, I have a Student case class which contains two fields roll number and name of the student. CRUD operations are performed on this Student data model.

Dependencies :

I am using SBT, so here is the relevant code from build.sbt

Scala data model as discussed above :

To get Akka HTTP and json4s to play nicely together, I am going to implement a custom trait that defines some helper methods for marshalling/unmarshalling to and from JSON along with necessary implicit values. 

Here’s our sample web server file that handles all CRUD related requests (GET, POST, PUT, DELETE) and responds with JSON. This file extends JsonHelper defined above and also shows the output generated by these helper methods to make your understanding even better.

Feel free to download and run the project. In case you face any problem comment below for the help.

Till then keep sharing, reading, blogging.

knoldus-advt-sticker

Written by 

Deepankar is a software consultant having more than 1.5 years of experience. He likes to keep up with the trending technologies. He is familiar with languages such as C, C++, Java, Scala and is currently working on Scala and Akka Http. His hobbies includes sports, music, travelling and yoga.

1 thought on “Akka http with json4s

Leave a Reply

%d bloggers like this: