Advertisement
Guest User

Untitled

a guest
Dec 4th, 2014
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.37 KB | None | 0 0
  1. case class LocationData(name: String, lat: Long, lng: Long)
  2.  
  3.   def parse4Square(jsonString: String): List[LocationData] = {
  4.     val json = spray.json.JsonParser(jsonString)
  5.  
  6.    
  7.     val items: List[JsObject] = json.asJsObject.fields("groups") match {
  8.       // get array of groups
  9.       case Some(JsArray(groups)) => groups flatMap { g =>
  10.         // get array of items in each group and glue them with flatMap
  11.         g.asJsObject.fields("items") match {
  12.           case Some(JsArray(itemsArray)) => itemsArray.map(_.asJsObject())
  13.           case _ => Nil
  14.         }
  15.       }
  16.       case _ => Nil
  17.     }
  18.  
  19.     // from every item
  20.     items.flatMap(i => {
  21.       // extract its venue
  22.       i.fields.get("venue") flatMap { venue => {
  23.        
  24.         // extract name
  25.         val venueObject = venue.asJsObject
  26.         val name = venueObject.fields.get("name") match {
  27.           case JsString(n) => n
  28.           case _ => "untitled location"
  29.         }
  30.        
  31.         venueObject.fields.get("location").flatMap(location => {
  32.           // if venue, lat and long exists - create a LocationData case class
  33.           List("lat", "lng").map(location.asJsObject.fields.get(_)) match {
  34.             case List(Some(JsNumber(lat), JsNumber(lng))) => Some(LocationData(name, lat.toLong, lng.toLong))
  35.             case _ => None  
  36.           }
  37.         })
  38.       }
  39.       }
  40.     })
  41.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement