Search code examples
jsonscalaspray-json

Spray JSON - deserialize field that may have different values


I am facing a problem of parsing a JSON with a field that may be Array or single object. In case hotel has multiple rooms, typical JsArray is returned. However, if it has only one type of room, it returns only one single object.

I am trying to parse this situation using case classes, especially List[Room] for this situation. This however fails in case only one single object is returned. Is there a way how to overcome this with case classes? If not, what is the solution to this problem?

Thank you very much.


Solution

  • You can use Either[A,B], Either can contain either instance of A or instance of B

    case class Hotel(data: Either[Room, List[Room]])