15.1. Creating a JSON String from a Scala Object
Problem
You’re working outside of a specific framework, and want to create a JSON string from a Scala object.
Solution
If you’re using the Play Framework, you can use its library to work with JSON, as shown in Recipes 15.13 and 15.14, but if you’re using JSON outside of Play, you can use the best libraries that are available for Scala and Java:
The Google Gson library (Java)
This recipe demonstrates the Lift-JSON and Gson libraries. (Json4s is a port of Lift-JSON, so it shares the same API.)
Lift-JSON solution
To demonstrate the Lift-JSON library, create an empty SBT test project. With Scala 2.10 and SBT 0.12.x, configure your build.sbt file as follows:
name := "Basic Lift-JSON Demo" version := "1.0" scalaVersion := "2.10.0" libraryDependencies += "net.liftweb" %% "lift-json" % "2.5+"
Next, in the root directory of your project, create a file named LiftJsonTest.scala:
import
scala.collection.mutable._
import
net.liftweb.json._
import
net.liftweb.json.Serialization.write
case
class
Person
(
name
:
String
,
address
:
Address
)
case
class
Address
(
city
:
String
,
state
:
String
)
object
LiftJsonTest
extends
App
{
val
p
=
Person
(
"Alvin Alexander"
,
Address
(
"Talkeetna"
,
"AK"
))
// create a JSON string from the Person, then print it
implicit
val
formats
=
DefaultFormats
val
jsonString
=
write
(
p
)
println
(
jsonString
)
}
This code creates a JSON string from the Person
instance, and prints it. When you run
the project with the sbt run
command, ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.