Scala Learning(1): 使用Pattern Matching表达JSON

这是一个挺能展现Scala编程方式的例子,对正在熟悉Scala这门语言的开发者很有帮助。

Representing JSON

用Scala来表达JSON(Java Script Object Notation)结构,

{
  "firstname" : "John",
  "lastname" : "Smith",
  "address" : {
    "street" : "21 2nd Street",
    "state" : "NY",
    "postalCode" : 10021
  },
  "phoneNumbers" : [
    { "type" : "home", "number" : "212 555-1234" },
    { "type" : "fax", "number : "646 555-4567" }
  ] 
}

Scala表示JSON的一种类结构:

abstract class JSON
case class JSeq (elems: List[JSON]) extends JSON
case class JObj (bindings: Map[String, JSON]) extends JSON
case class JNum (num: Double) extends JSON
case class JStr (str: String) extends JSON
case class JBool(b: Boolean) extends JSON
case object JNull extends JSON

Example

val data = JObj(Map(
  "firstName" -> JStr("John"),
  "lastName" -> JStr("Smith"),
  "address" -> JObj(Map(
    "street" -> JStr("21 2nd Street"),
    "state" -> JStr("NY"),
    "postalCode" -> JNum(10021)
  )),
  "phoneNumbers" -> JSeq(List(
    JObj(Map(
      "type" -> JStr("home"), "number" -> JStr("212 555-1234")
    )),
    JObj(Map(
      "type" -> JStr("fax"), "number"-> JStr("646 555-4567")
    )) 
  ))
))

利用Pattern Matching,展示一个输出JSON string串的方法:

def show(json: JSON): String = json match {
  case JSeq(elems) =>
    "[" + (elems map show mkString ", ") + "]"
  case JObj(bindings) =>
    val assocs = bindings map {
      case (key, value) => "\"" + key + "\": " + show(value)
    }
  "{" + (assocs mkString ", ") + "}"
  case JNum(num) => num.toString
  case JStr(str) => '\"' + str + '\"'
  case JBool(b) => b.toString
  case JNull => "null"
}

参考自 Principles of Reactive Programming

全文完 :)

上一篇:监视服务器实例上的全文搜索活动


下一篇:Android 3.0 r1 API中文文档(108) —— ExpandableListAdapter