Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 ={case field => field})
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)
case _ =>
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"))
val simple = json.extract[Simple]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.