Skip to content

Instantly share code, notes, and snippets.

@Centaur
Created May 9, 2014 03:30
Show Gist options
  • Save Centaur/b62ce5d7b56c886c51bf to your computer and use it in GitHub Desktop.
Save Centaur/b62ce5d7b56c886c51bf to your computer and use it in GitHub Desktop.
json4s customized serialization
import java.util.Date
import org.json4s._
import native.JsonMethods._
import org.json4s.native.Serialization
val body = """{
|"_id": "1223456a171",
|"siteid": "abc",
|"serverid": "3266",
|"weekOfYear": 2014001,
|"extno": "6210",
|"startTime": "\/Date(1399598421)\/",
|"endTime": "\/Date(1399598601)\/"
|}"""
case class RecIndex(id: String, siteId: String, serverId: String, weekOfYear: BigInt, extNo: String, startTime: Date, endTime: Date)
val DateTimeExtractor = """\/Date\((\d+)\)\/""".r
def convert(jsonStr: String): Date = jsonStr match {
case DateTimeExtractor(time) => new Date(time.toLong)
}
val recIndexFormat: Formats => (PartialFunction[JValue, RecIndex], PartialFunction[Any, JValue]) = { format: Formats =>
val reader: PartialFunction[JValue, RecIndex] = {
case JObject(JField("_id", JString(id)) ::
JField("siteid", JString(siteId)) ::
JField("serverid", JString(serverId)) ::
JField("weekOfYear", JInt(weekOfYear)) ::
JField("extno", JString(extNo)) ::
JField("startTime", JString(startTime)) ::
JField("endTime", JString(endTime)) :: Nil) =>
RecIndex(id, siteId, serverId, weekOfYear, extNo, convert(startTime), convert(endTime))
}
val writer: PartialFunction[Any, JValue] = {
case r: RecIndex => JObject(
JField("_id", JString(r.id)),
JField("siteid", JString(r.siteId)),
JField("serverid", JString(r.serverId)),
JField("weekOfYear", JInt(r.weekOfYear)),
JField("extno", JString(r.extNo)),
JField("startTime", JString( s"""\/Date(${r.startTime.getTime})\/""")),
JField("endTime", JString( s"""\/Date(${r.endTime.getTime})\/"""))
)
}
(reader, writer)
}
class RecIndexFormat extends CustomSerializer[RecIndex](recIndexFormat)
implicit val formats = Serialization.formats(NoTypeHints) + new RecIndexFormat
parse(body.stripMargin).extract[RecIndex]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment