scala/liftweb serializing json

跟風遠走 提交于 2020-01-16 18:34:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!