jsonscalaunmarshallingspray-jsonscala-option

Scala. How to Unmarshall Option values using json spray?


I'm using json-spray library to unmarshall a json array. Here is the code.

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

 def unmarshalProfiles(response: HttpResponse): Future[Array[Profile]] = {
        implicit val profileFormat = jsonFormat16(Profile)
        println("[RES - SUCCESS] Request returned with " + response.status)
        return  Unmarshal(response.entity).to[Array[Profile]]
      }

The remote server writes its response as a json array. No problems if the response is fullfilled with one or more items. However, if no Profile item is available, the server returns null (not an empty array) and while unmarshalling I get the error 'Expected Array as JsArray, but got null'.

I thought that a good option would be to wrap the Array[Profile] into a Option object. So I changed the code into the following.

 def unmarshalProfiles(response: HttpResponse): Future[Option[Array[Profile]]] = {
        implicit val profileFormat = jsonFormat16(Profile)
        println("[RES - SUCCESS] Request returned with " + response.status)
        return  Unmarshal(response.entity).to[Option[Array[Profile]]]
      }

Still, when the response is a null object, I'm obtaining the same error. Does exist a way to unmarshall a Option object when it is None? Thanks in advance!


Solution

  • You have the option to work all along with options. That means, to define your method like that:

    def unmarshalProfiles(response: HttpResponse)(implicit mat: Materializer): Future[Option[Array[Profile]]] = {
      implicit val profileFormat = jsonFormat16(Profile)
      Unmarshal(Option(response.entity)).to[Option[Array[Profile]]]
    }
    

    Then null will be marshalled into None, and an existing array will become Some(...)