Perhaps I found a bug in splash-json. I get a Null Pointer Exception when I try to get the json of an object that has a field of the type itself. Example:
case class TestItem(subitems: Option[List[TestItem]]) object MyJsonProtocol extends DefaultJsonProtocol { implicit val testItemFormat: RootJsonFormat[TestItem] = jsonFormat(TestItem, "subitems") } import MyJsonProtocol._ object TestNPE { def main(args: Array[String]) { val subitems = List(TestItem(None)) val item: TestItem = TestItem(Option(subitems)) val jsonAst = item.toJson val json = jsonAst.prettyPrint println(json) } }
And call-stack is
Exception in thread "main" java.lang.NullPointerException at spray.json.PimpedAny.toJson(package.scala:40) at spray.json.CollectionFormats$$anon$1$$anonfun$write$1.apply(CollectionFormats.scala:26) at spray.json.CollectionFormats$$anon$1$$anonfun$write$1.apply(CollectionFormats.scala:26) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) at scala.collection.immutable.List.foreach(List.scala:309) at scala.collection.TraversableLike$class.map(TraversableLike.scala:244) at scala.collection.AbstractTraversable.map(Traversable.scala:105) at spray.json.CollectionFormats$$anon$1.write(CollectionFormats.scala:26) at spray.json.CollectionFormats$$anon$1.write(CollectionFormats.scala:25) at spray.json.PimpedAny.toJson(package.scala:40) at spray.json.StandardFormats$OptionFormat.write(StandardFormats.scala:34) at spray.json.StandardFormats$OptionFormat.write(StandardFormats.scala:32) at spray.json.ProductFormats$class.productElement2Field(ProductFormats.scala:473) at spray.json.MyJsonProtocol$.productElement2Field(TestNPE.scala:5) at spray.json.ProductFormats$$anon$1.write(ProductFormats.scala:32) at spray.json.ProductFormats$$anon$1.write(ProductFormats.scala:30) at spray.json.PimpedAny.toJson(package.scala:40) at spray.json.TestNPE$.main(TestNPE.scala:18) at spray.json.TestNPE.main(TestNPE.scala)
Sooo I tried to fix it myself, but my Scala knowledge is still not strong enough. NPE is here when it tries to convert an internal TestItem . The write function parameter is null at this point.
Could you explain to me why, instead, I do not mean it? I see in the debugger that instead of using my implicit write contains the value of some magic field evidence$x$y , which changes as it goes deeper in the call chain . I do not know what is this. I feel this is context related, but reading the relevant chapter did not help.
source share