Skip to content

Instantly share code, notes, and snippets.

@iron9light
Created September 24, 2012 08:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iron9light/3774889 to your computer and use it in GitHub Desktop.
Save iron9light/3774889 to your computer and use it in GitHub Desktop.
a json-lift Serializer to replace field name.
package sandbox
import net.liftweb.json._
case class FieldSerializer2[A: Manifest](
serializer: PartialFunction[(String, Any), Option[(String, Any)]] = Map(),
deserializer: PartialFunction[JField, JField] = Map()
) extends Serializer[A] {self =>
val Class = implicitly[Manifest[A]].erasure
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), A] = {
case (TypeInfo(Class, _), json) =>
val newJson = json match {
case JObject(fields) =>
val newFields = fields.map(deserializer.orElse{case field => field})
JObject(newFields)
case _ => json
}
newJson.extract(format0, manifest[A])
}
def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case x =>
val jvalue = Extraction.decompose(x)(format0)
jvalue match {
case JObject(fields) =>
val s: PartialFunction[(String, Any), Option[(String, Any)]] = serializer.orElse{case y => Some(y)}
val newFields = for {
JField(name, value) <- fields
(newName, newValue: JValue) <- s(name, value)
} yield JField(newName, newValue)
JObject(newFields)
case _ =>
jvalue
}
}
def format0(implicit format: Formats) = new Formats {
val dateFormat = format.dateFormat
override val typeHintFieldName = format.typeHintFieldName
override val parameterNameReader = format.parameterNameReader
override val typeHints = format.typeHints
override val customSerializers = format.customSerializers.filterNot(_ eq self)
override val fieldSerializers = format.fieldSerializers
}
}
package sandbox
import net.liftweb.json._
import FieldSerializer._
object TestApp extends App {
case class Simple(x: String)
implicit val formats = DefaultFormats +
FieldSerializer2[Simple](renameTo("x", "y"), renameFrom("y", "x"))
val json = Extraction.decompose(Simple("test"))
println(json)
val simple = json.extract[Simple]
println(simple)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment