scala/liftweb序列化json [英] scala/liftweb serializing json

查看:111
本文介绍了scala/liftweb序列化json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将net.liftweb解析器用于scala

I am using net.liftweb parser for scala

我有一个像这样的json

I have a json like this

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

k2是一个可选字段,json可能有也可能没有.我将其提取到案例类中

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

案例类MyCC(k1:字符串,k2:列表[String])

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

当json转换为case类时,如果k2不存在,则将其反序列化为空列表.问题是在转换回json时,如果它是一个空列表,我如何使解析器不对该字段进行序列化.

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"}

这篇关于scala/liftweb序列化json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆