August 2013
Intermediate to advanced
720 pages
16h 23m
English
You have a JSON string that represents an array of objects, and you need to deserialize it into objects you can use in your Scala application.
Use a combination of methods from the Lift-JSON library. The
following example demonstrates how to deserialize the string jsonString into a series of EmailAccount objects, printing each object as
it is deserialized:
importnet.liftweb.json.DefaultFormatsimportnet.liftweb.json._// a case class to match the JSON datacaseclassEmailAccount(accountName:String,url:String,username:String,password:String,minutesBetweenChecks:Int,usersOfInterest:List[String])objectParseJsonArrayextendsApp{implicitvalformats=DefaultFormats// a JSON string that represents a list of EmailAccount instancesvaljsonString="""{"accounts": [{ "emailAccount": {"accountName": "YMail","username": "USERNAME","password": "PASSWORD","url": "imap.yahoo.com","minutesBetweenChecks": 1,"usersOfInterest": ["barney", "betty", "wilma"]}},{ "emailAccount": {"accountName": "Gmail","username": "USER","password": "PASS","url": "imap.gmail.com","minutesBetweenChecks": 1,"usersOfInterest": ["pebbles", "bam-bam"]}}]}"""// json is a JValue instancevaljson=parse(jsonString)valelements=(json\\"emailAccount").childrenfor(acct<-elements){valm=acct.extract[EmailAccount]println(s"Account: ${m.url}, ${m.username}, ${m.password}")println(" Users: " ...
Read now
Unlock full access