CodexBloom - Programming Q&A Platform

NullPointerException When Using Custom JsonFormat with Circe in Scala 2.13.6

👀 Views: 23 💬 Answers: 1 📅 Created: 2025-06-29
scala circe json Scala

I'm reviewing some code and Quick question that's been bugging me - I'm stuck on something that should probably be simple... I'm working with a `NullPointerException` when trying to parse JSON using a custom `JsonFormat` with Circe in Scala 2.13.6. The scenario seems to arise when the JSON input has missing fields which are supposed to be optional in my case. I created a case class like this: ```scala case class User(name: String, age: Option[Int]) ``` And my custom `JsonFormat` is defined as follows: ```scala import io.circe.{Decoder, Encoder} import io.circe.generic.semiauto._ object User { implicit val userDecoder: Decoder[User] = deriveDecoder[User] implicit val userEncoder: Encoder[User] = deriveEncoder[User] } ``` When I try to decode a JSON string like this: ```scala val jsonString = "{\"name\": \"John\"}" // age field is missing val userResult = io.circe.parser.decode[User](jsonString) ``` I expect `userResult` to return `Right(User("John", None))`, but I instead get a `NullPointerException`. I’ve checked that the JSON string is correctly formatted, and I've also tried adding default values in the case class, but I still encounter this behavior. I suspect that the scenario might be related to how Circe handles missing fields for optional types. I've gone through the Circe documentation and couldn't find a concrete solution. I've also attempted to manually handle the decoding process, but it still throws an exception. Could someone guide to understand why this is happening and how I can correctly decode the JSON without working with a `NullPointerException`? This is part of a larger API I'm building. What's the best practice here? I've been using Scala for about a year now. This issue appeared after updating to Scala 3.9. Has anyone dealt with something similar? This is my first time working with Scala 3.11. I'm open to any suggestions.