lift-json why method rename in FieldSerializer keep original field?

255 views
Skip to first unread message

mmliu

unread,
Sep 13, 2012, 8:47:41 AM9/13/12
to lif...@googlegroups.com
I get a case class like this:
 
  case class Simple(x: String)

and I wanna change the field name from x to y when serialize it into json,so I do:

implicit val formats = DefaultFormats +
   
FieldSerializer[Simple](renameTo("x","y"),renameFrom("y", "x"))

I thought the output of

Serialization.write(Simple("test"))

would be : {"y":"test"}

however it is {"y":"test","x":"test"}

is this a expected behavior? what should I do if I want the result be :
{"y":"test"} ?

ps.check out http://stackoverflow.com/questions/11880717/can-i-use-lifts-fieldserializer-to-change-a-field-on-serialization for more

IL

unread,
Sep 22, 2012, 1:16:56 PM9/22/12
to lif...@googlegroups.com
https://github.com/lift/framework/blob/2.4-release/core/json/src/main/scala/net/liftweb/json/Extraction.scala#L104

It seems that lift-json only wanna add the newName field but not replace the old one.
I'm not sure whether it's a bug, or we just need to add a notice for this.

Now you can replace the name with a CustomSerializer

  implicit val formats = DefaultFormats +
    new CustomSerializer[Simple](ser => ( {
      case JObject(JField("y", JString(x)) :: Nil) => Simple(x)
    }, {
      case simple: Simple => JObject(JField("y", simple.x) :: Nil)
    }))

mmLiu

unread,
Sep 24, 2012, 3:10:39 AM9/24/12
to lif...@googlegroups.com
Thanks IL

CustomSerializer works.

--
--
Lift, the simply functional web framework: http://liftweb.net
Code: http://github.com/lift
Discussion: http://groups.google.com/group/liftweb
Stuck? Help us help you: https://www.assembla.com/wiki/show/liftweb/Posting_example_code
 
 
 



--
Best Regards

----------------------
刘明敏 | mmLiu

IL

unread,
Sep 24, 2012, 4:25:00 AM9/24/12
to lif...@googlegroups.com
I wrote the FieldSerializer2 for you


Now you can do this:

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) // JObject(List(JField(y,JString(test))))

  val simple = json.extract[Simple]

  println(simple) // Simple(test)

}

P.S. 中国人吗?多交流。

liming hu

unread,
Sep 11, 2013, 2:39:27 PM9/11/13
to lif...@googlegroups.com
This is a great post.
I have a related json rendering question:

Suppose one field of a case class is null, how can it be ignored?

Thanks,

Liming
Reply all
Reply to author
Forward
0 new messages