15.3. Creating a Simple Scala Object from a JSON String
Problem
You need to convert a JSON string into a simple Scala object, such as a Scala case class that has no collections.
Solution
Use the Lift-JSON library to convert a JSON string to an instance of a case class. This is referred to as deserializing the string into an object.
The following code shows a complete example of how to use
Lift-JSON to convert a JSON string into a case class named MailServer. As its name implies, MailServer represents the information an email
client needs to connect to a server:
importnet.liftweb.json._// a case class to represent a mail servercaseclassMailServer(url:String,username:String,password:String)objectJsonParsingExampleextendsApp{implicitvalformats=DefaultFormats// simulate a json stringvaljsonString="""{"url": "imap.yahoo.com","username": "myusername","password": "mypassword"}"""// convert a String to a JValue objectvaljValue=parse(jsonString)// create a MailServer object from the stringvalmailServer=jValue.extract[MailServer]println(mailServer.url)println(mailServer.username)println(mailServer.password)}
In this example, the jsonString
contains the text you’d expect to receive if you called a web service
asking for a MailServer instance.
That string is converted into a Lift-JSON JValue object with the parse function:
valjValue=parse(jsonString)
Once you have a JValue object,
use its extract method to create a
MailServer object:
valmailServer ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access