Skip to content

Instantly share code, notes, and snippets.

@kjetilv
Created February 6, 2011 13:27
Show Gist options
  • Save kjetilv/813365 to your computer and use it in GitHub Desktop.
Save kjetilv/813365 to your computer and use it in GitHub Desktop.
Structured JSON extraction - what to do?
import org.specs.Specification
import org.specs.runner.{Runner, JUnit}
class ExtractJSONTest extends Runner(ExtractJSON) with JUnit
object ExtractJSON extends Specification {
import net.liftweb.json._
import JsonParser._
implicit val formats = DefaultFormats
val joe = """
{ "name" : "joe",
"street" : "nonestreet",
"city" : "oslo",
"phone" : "99393939"
"email" : "joe@nonestreet.oslo"
}"""
val titledJoe = """
{ "name" : "joe",
"title" : "herr",
"street" : "nonestreet",
"city" : "oslo",
"phone" : "99393939"
"email" : "joe@nonestreet.oslo"
}"""
case class Joe(name: String, title: Option[String])
case class ResidentJoe(name: String, title: Option[String], address: Address)
case class OptionalResidentJoe(name: String, title: Option[String], address: Option[Address])
case class Address(street: String, city: String)
case class Contact(phone: String, email: String)
"Simple Joe extraction, with no title field" in {
parse(joe).extract[Joe] mustEqual Joe("joe", None)
}
"Titled Joe extraction - Herr Joe" in {
parse (titledJoe).extract[Joe] mustEqual Joe("joe", Some("herr"))
}
"Address extraction using address-related fields" in {
parse(joe).extract[Address] mustEqual Address("nonestreet", "oslo")
}
"Contact extraction using contact-related fields" in {
parse(joe).extract[Contact] mustEqual Contact("99393939", "joe@nonestreet.oslo")
}
"Optionally resident Joe extraction, with optional Address" in {
parse (joe).extract[OptionalResidentJoe] mustEqual OptionalResidentJoe("joe", None, None)
}
// Fails: (But would be very nifty if it worked)
"Resident Joe extraction, with a real Address, fails" in {
parse (joe).extract[ResidentJoe] mustEqual ResidentJoe("joe", None, Address("nonestreet", "oslo"))
}
// Fails: (But would be very nifty if it worked)
"Resident, titled Joe extraction, with real Address, same as above" in {
parse (titledJoe).extract[ResidentJoe] mustEqual ResidentJoe("joe", Some("herr"), Address("nonestreet", "oslo"))
}
}
@kjetilv
Copy link
Author

kjetilv commented Feb 6, 2011

My post to the liftweb mailing list is being approved (I hope), but in the meantime: The gist of this gist is that I want to express Joe as a structured case class, with sub-levels Address and Contact, from the flat JSON. However, as it is, this requires the presence of structure (in particular, it requires the fields "contact" and "address") in the JSON.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment