Skip to content

Instantly share code, notes, and snippets.

@farmdawgnation
Last active December 10, 2015 02:58
Show Gist options
  • Save farmdawgnation/4371012 to your computer and use it in GitHub Desktop.
Save farmdawgnation/4371012 to your computer and use it in GitHub Desktop.
The ContactSerializer for use with the Constant Contact API I'm developing.
{
"email_addresses":[{
"email_address":"[email protected]"
}],
"action_by":"ACTION_BY_VISITOR",
"id":0,
"name":{
"first_name":"Hubert",
"middle_name":"S",
"last_name":"Williams"
},
"addresses":[],
"notes":[],
"custom_fields":[],
"lists":[]
}
case class ContactPhones( home_phone:Option[String] = None, work_phone:Option[String] = None,
cell_phone:Option[String] = None)
case class ContactName( first_name:Option[String] = None, middle_name:Option[String] = None,
last_name:Option[String] = None)
case class Contact(email_addresses:List[EmailAddress], action_by:String, id:Long = 0,
status:Option[Status.Value] = None, prefix_name:Option[String] = None,
name:Option[ContactName] = None, job_title:Option[String] = None,
department_name:Option[String] = None, company_name:Option[String] = None,
phone:Option[ContactPhones] = None, fax:Option[String] = None,
addresses:List[Address] = List(), notes:List[Note] = List(),
custom_fields:List[CustomField] = List(), confirmed:Option[Boolean] = None,
insert_time:Option[DateTime] = None, last_update_time:Option[DateTime] = None,
lists:List[ContactList] = List(), source:Option[String] = None,
source_details:Option[String] = None, source_is_url:Option[Boolean] = None,
web_url:Option[String] = None)
object ContactSerializer extends Serializer[Contact] {
private val Class = classOf[Contact]
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Contact] = {
case (TypeInfo(Class, _), json) =>
json.extract[Contact]
}
def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case x:Contact =>
// Decompose as a normal case class.
implicit val formats = DefaultFormats
val contactJson = decompose(x)
// Extract names and phone numbers to top level
contactJson.transform {
case JField("name", contactNameJson) =>
val contactNameInfo = contactNameJson.extract[ContactName]
("first_name" -> contactNameInfo.first_name) ~
("middle_name" -> contactNameInfo.middle_name) ~
("last_name" -> contactNameInfo.last_name)
}
}
}
{
"email_addresses":[{
"email_address":"[email protected]"
}],
"action_by":"ACTION_BY_VISITOR",
"id":0,
"first_name":"Hubert",
"middle_name":"S",
"last_name":"Williams",
"addresses":[],
"notes":[],
"custom_fields":[],
"lists":[]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment