简体   繁体   English

使用Json4s时,如何从json中删除空/无效字段?

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

If I have the following: 如果我有以下内容:

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

That would output something like: 那将输出类似:

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

The expected output I want is: 我想要的预期输出是:

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

How can I accomplish this? 我该怎么做?

This works OKAY, but imagine if I had a value object with say 15 fields somehow, then the tostring gets very big. 这行得通,但是想像一下,如果我有一个带有15个字段的值对象,那么字符串就会变得很大。

Based on your expected resposne, you can just use Json4s's built in method write . 根据您的预期响应,您可以使用Json4s的内置方法write


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

The imports that you need is 您需要的进口是

import org.json4s.native.Serialization.write                                          

Turns out, Json4s is smart enough to omit fields which are "None" 事实证明,Json4s足够聪明,可以忽略“无”字段

So the end result for over 所以最终结果超过了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM