Scala / liftweb serializing json

I am using net.liftweb parser for scala

I have a json like

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

k2 - optional field, json may or may not have it. I retrieve this in the case class

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

When json is converted to the case class, if k2 is missing, it is deserialized to an empty list. The problem is converting back to json, how can I get the analyzer not to serialize this field if it is an empty list.

0
source share
1 answer

You should create a custom serializer . This should be good 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"}
0
source

All Articles