使用 Json4s 时如何从 json 中删除 empty/invalid 字段?

How can I strip out empty/invalid fields from json when using Json4s?

如果我有以下情况:

object Json4sTest extends App {
  val info = new TestObject("Johnny", "USA")
  println(info)
}

case class TestObject(
  name: String,
  companyName: String,
  var countryCode: Option[String] = None,
  var countryName: Option[String] = None,
  var zip: Option[Int] = None
) {

  override def toString: String = {
    compact(render(
      ("name" -> name) ~
      ("companyName" -> countryCode) ~
      ("countryCode" -> (if (countryCode.isDefined) countryCode.get else StringUtils.EMPTY)) ~
      ("countryName" -> (if (countryName.isDefined) countryName.get else StringUtils.EMPTY)) ~
      ("zip" -> (if (zip.isDefined) zip.get else -1))
    ))
  }
}

这将输出如下内容:

{"name":"Johnny","companyName":"Some Company","countryCode":"","countryName":"","zip":-1}

我想要的预期输出是:

{"name":"Johnny","companyName":"Some Company"}

我怎样才能做到这一点?

这可以正常工作,但想象一下,如果我有一个值对象以某种方式包含 15 个字段,那么 tostring 会变得非常大。

事实证明,Json4s 足够聪明,可以省略 "None"

的字段

所以最终结果超过了

override def toString: String = {
   compact(render(
    ("name" -> name) ~
    ("companyName" -> companyName) ~
    ("countryCode" -> countryCode) ~
    ("countryName" -> countryName) ~
    ("zip" -> zip)
  ))
}

根据您的预期响应,您可以只使用 Json 4s 的内置方法 write


  override def toString: String = {
      implicit val formats = DefaultFormats
      write(this)
    }
 val info = new TestObject("Johnny", "USA")<br>
//> info  : TestObject = {"name":"Johnny","companyName":"USA"}
 </pre> 

您需要的导入是

import org.json4s.native.Serialization.write