简体   繁体   中英

scala/liftweb serializing json

I am using net.liftweb parser for scala

I have a json like this

  {
  "k1":"v1",
  "k2":["v21", "v22", "v23"]
  }

k2 is an optional field, json might or might not have it. I extract this into a case class

case class MyCC (k1: String, k2: List[String])

When json is converted to case class, if k2 is not present then it is deserialized into empty list. The issue is while converting back to json, how could i make the parser not serialize this field if it is an empty list.

You should create custom serializer . This should be fine for your case:

import org.json4s._
import org.json4s.native.Serialization.write
class NilSerializer extends CustomSerializer[List[String]](format => ( {
    case JNothing => Nil
  }, {
    case Nil => JNothing
}))

implicit val formats = DefaultFormats + new NilSerializer
println(write(MyCC("key", Nil)))
>> {"k1":"key"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM