问题
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.
回答1:
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"}
来源:https://stackoverflow.com/questions/29710814/scala-liftweb-serializing-json