0

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.

iCodeLikeImDrunk
  • 17,085
  • 35
  • 108
  • 169

2 Answers2

1

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                                          
mohit
  • 4,968
  • 1
  • 22
  • 39
0

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)
  ))
}
iCodeLikeImDrunk
  • 17,085
  • 35
  • 108
  • 169