Akka http with json4s

Knoldus Inc.
Knoldus - Technical Insights
2 min readJun 21, 2018

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 :

https://gist.github.com/deepankar14693/84d2f2fbe03b70a8ef3d48a9d8ab4e9e
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.
https://gist.github.com/deepankar14693/41044ec6062d4e696dc2ee7b7dcbeb87
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.
https://gist.github.com/deepankar14693/9fdae28e99755412dbbb3f781332bbe5

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

--

--

Knoldus Inc.
Knoldus - Technical Insights

Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage | www.knoldus.com