简体   繁体   中英

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.

Based on your expected resposne, you can just use Json4s's built in method 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"

So the end result for over

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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