Sensis Developer Centre - SAPI Forums

API Forum

RSS Feed

Scala APIExample

    • Hound
    • Topic created 7 years ago

    Here's a Scala transliteration of the Java API Example. It may not be 100% correct as I don't have my API key yet, but the parsing portion works.

    This example requires Twitter's JSON library from http://scala-tools.org/repo-releases/com/twitter/json_2.8.0/2.1.4/json_2.8.0-2.1.4.jar

    It is not quite idiomatic Scala, but it's close enough. It returns a List of Listings rather than printing them out.

    There's a lot of annoying casting involved after the JSON parsing. I suspect the SJSON library will do this better, but I'm yet to grok it. If it improves the code, then I'll update this sample.



    import io.Source
    import com.twitter.json.Json
    import java.net.URLEncoder._

    case class Listing(name: String, address: String)
    class SensisApiExample {
    private val apiKey = "..."

    def searchByType(query: String, location: String) = {
    val url = "http://api.sensis.com.au/20110229/search?key=%s&query=%s&location=%s"
    .format(apiKey, encode(query, "UTF-8"), encode(location, "UTF-8"))
    val json = Json.parse(Source.fromURL(url).mkString).asInstanceOf[Map[Any,Any]]
    val (code, message) = (json("code").asInstanceOf[Int], json("message").asInstanceOf[String])
    println("Total results found: %d".format(json("totalResults")))

    def parse(results: List[Map[Any, Any]]) = {
    results.map{map =>
    val name = map("name").asInstanceOf[String]
    val place = map("primaryAddress").asInstanceOf[Map[Any,Any]].apply("addressLine").asInstanceOf[String]
    Listing(name, place)
    }
    }

    val results = code match {
    case 200 => parse(json("results").asInstanceOf[List[Map[Any,Any]]])
    case 206 => {
    println("Note: %s".format(message))
    parse(json("results").asInstanceOf[List[Map[Any,Any]]])
    }
    case _ => throw new RuntimeException("API returned error: %s, code: %d".format(message, code))
    }
    }
    }

    Message edited by Hound 7 years ago

    Tags

  1. Hound7 years ago

    See https://gist.github.com/852706 for better formatting

[ Page 1 of 1 ]