Play 2.3 implicit json conversion causes null pointer exception

后端 未结 2 1132
孤城傲影
孤城傲影 2021-01-01 22:20

I\'m trying to parse json into my case class DealFormMap

case class DealFormMap(limit: Option[Int], filter: Option[DealFormFilterMap])
case clas         


        
2条回答
  •  渐次进展
    2021-01-01 22:52

    The problem is the initialization order. dealFormMapReads depends on the implicit dealFormFilterMapReads, which isn't defined until after. It will compile because the implicit is found, even though it hasn't been initialized, so dealFormMapReads is read as null, which eventually causes the NPE.

    Lazily loading will fix it:

    implicit val dealFormMapReads: Reads[DealFormMap] = (
         (JsPath \ "limit").readNullable[Int] and
         (JsPath \ "filter").lazyReadNullable[DealFormFilterMap](dealFormFilterMapReads)
    )(DealFormMap)
    

    Or you could just swap the order in which the Reads are defined.


    The NPE thrown here is similar to this example:

    case class A(i: Int)
    
    object Test {
         val test = a.toString
         val a = A(1)
    }
    
    // Compiles up to here
    
    Test.test // throws NPE, because `a` was not initialized before `test`
    

提交回复
热议问题