Chapter 5. Handling JSON

 

This chapter covers

  • Consuming and producing JSON using the Scalatra JSON module
  • Handling heterogeneity when working with JSON
  • Using JSONP

JSON is a common data interchange format for semistructured data. It’s human-readable and supports primitive, array, and object values. Additionally, for web services it’s the natural data format of the browser, due to its close relationship with JavaScript.

Scalatra offers a module that supports an application working with JSON. This chapter covers its use with practical examples taken from the food domain. Who knows, maybe you’ll also learn a useful recipe!

5.1. Introducing JsonSupport

The Scalatra JSON module extends an application’s request handling with two facets:

  • An incoming JSON request is parsed to a JSON value.
  • A JSON value is written to the response as JSON text, as a result of a route action.

Let’s see how you can add JSON support to an application.

5.1.1. Adding JSON support to an application

Because Scalatra’s JSON support is an optional module, it needs to be added as a dependency to the sbt build definition:

libraryDependencies ++= Seq(
  "org.scalatra" %% "scalatra-json" % ScalatraVersion,
  "org.json4s"   %% "json4s-jackson" % "3.3.0")

5.2. Producing and consuming JSON

5.3. Customizing JSON support and handling mismatches

5.4. JSONP

5.5. Summary