Question

i'm got an error:

spray.json.ProductFormats$class.productElement2Field NullPointerException

Here is my code for json deserialisation:

object DomainJsonProtocol extends DefaultJsonProtocol {
implicit val loginInfoFormat = jsonFormat(LoginInfo, "userid", "email", "password", "rememberme")
implicit val requestStatusFormat = jsonFormat(RequestStatus, "status", "message")
implicit val requestHolderFormat = jsonFormat(RequestHolder, "requestStatus", "loginInfo")
}

case class RequestHolder(requestStatus : RequestStatus, loginInfo: LoginInfo) {
  def this(requestStatus : RequestStatus) = this(requestStatus, null)
}
case class LoginInfo(userid: Int, email: String, password: String, rememberme: Boolean)
case class RequestStatus(status : Int, message: String)

val requestHolder = content.asJson.convertTo[RequestHolder] //The error is hereHere is 

I guess it could be because of the overloaded constructors in the class RequestHolder.

upd: The json content is:

{"requestStatus":{"status":0,"message":""},"loginInfo":{"userid":0,"email":"123","password":"123","rememberme":false}}
Was it helpful?

Solution 2

I'm found solution in the official spray mailing list, the solution is use Option[MyClass] = None in the constructor, instead the override constructors with nulls, for instance, my class definition look like:

case class RequestHolder(requestStatus : RequestStatus,  loginInfo: Option[LoginInfo] = None)

and now parsing works fine!

OTHER TIPS

I had a similar issue and my problem was due to the order I defined the jsonreaders. I had an example like this:

implicit val multipleThings: RootJsonFormat[Things] = jsonFormat1(Things)
implicit val singleThing: RootJsonFormat[Thing] = jsonFormat1(Thing)

Here the Things case class had a list of Thing's.

That didn't work because the first one implicitly needs the second one. Reordering them like this:

implicit val singleThing: RootJsonFormat[Thing] = jsonFormat1(Thing)
implicit val multipleThings: RootJsonFormat[Things] = jsonFormat1(Things)

Made it work.

All credit to: https://stackoverflow.com/a/29280316/1539208

I had a similar issue and for me it was lazyFormat that fixed it:

implicit val requestStatusFormat: JsonFormat[RequestStatus] = lazyFormat(jsonFormat2(RequestStatus))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top