简体   繁体   English

Scala:检查案例类树是否不包含任何null

[英]Scala: check that a case class tree doesn't contain any null

I use a Scala json serializer and just discovered that it doesn't set default values to case classes en deserialization, but instead set these missing values to null. 我使用了Scala json序列化程序,只是发现它没有为反序列化的case类设置默认值,而是将这些缺少的值设置为null。

Fortunatly it didn't damage much my system until now mostly because of CRUD only fields being set to null, but in the future, I absolutely want to enforce that my JSON payloads do not have any null values. 幸运的是,直到现在,它并没有对我的系统造成太大的损害,主要是因为仅将CRUD字段设置为null,但是在将来,我绝对希望强制我的JSON有效负载不包含任何null值。

My Json payloads are generally some kind of tree of case classes with lists and primitives. 我的Json有效负载通常是带有列表和基元的案例类树。 It is generally pretty simple, like a case class Person(addresses: List[Address], name: String, ...) with case class Address(street: String, number: Int) ... 这通常非常简单,例如case class Person(addresses: List[Address], name: String, ...)case class Address(street: String, number: Int) ...


  • Is there a way to ensure that a case class has no null field in it? 有没有办法确保案例类中没有空字段?
  • In case a null is found, is there a way to set it automatically to the default value instead of null? 如果找到null,是否可以将其自动设置为默认值而不是null?
  • Would it work for nested case classes? 它适用于嵌套案例类吗?

I guess there's something to do with the Product trait but don't really know where to start. 我想这与Product特质有关,但真的不知道从哪里开始。

You can add a requirement on the case class so serialization will fail: 您可以在案例类上添加要求,以便序列化将失败:

case class Person(  name: String, 
                    ssn: String,
                    homePhone: Option[Long],
                    cellPhone: Option[Long]){

  require(homePhone.isDefined || cellPhone.isDefined, "Person requires at least one phone number")
  require(ssn.length() == 9 && ssn.forall(Character.isDigit(_)), "ssn must be a String of 9 digits")
}

Can be this a solution? 这可以解决吗?

def isCaseClassEmpty(product: Product): Boolean =
    product.productIterator.forall {
      case None => true
      case Some(x: Product) => isCaseClassEmpty(x)
      case _ => false
    }

case class Inner(b: Option[Int])
case class Root(a: Option[String]: inner: Option[Inner])

val root = Root(None, None))
isCaseClassEmpty(root) // true

val root = Root(None, Some(Inner(None)))
isCaseClassEmpty(root) // true

val root = Root(None, Some(Inner(Some(5))))
isCaseClassEmpty(root) // false

val root = Root(Some("test"), None)
isCaseClassEmpty(root) // false

Cheers :-) 欢呼声:-)

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

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