Search code examples
jsonscalaenumsspray-json

How to model finite set of values of enum-like type for (de)serialization?


I am using Spray-json 1.3.1. I have the following JSON message:

{
   "results": [{
   ... NOT IMPORTANT PART HERE ...
   }],
   "status": "OK"
}

Trivially, this can be deserialized to status String field via

case class Message[T](results: List[T], status: String)

with custom Protocol

object MessageProtocol extends DefaultJsonProtocol {
  implicit def messageFormat[T: JsonFormat] = jsonFormat2(Message.apply[T])
}

Since status field can be one of OK, ZERO_RESULTS, OVER_QUERY_LIMIT having this field as a String makes no sense. As I am coming from Java background I tried enums in Scala implemented as follows:

case class Message[T](results: List[T], status: Status)
object Status extends Enumeration{
  type Status = Value
  val OK,ZERO_RESULTS,OVER_QUERY_LIMIT, REQUEST_DENIED, INVALID_REQUEST,UNKNOWN_ERROR = Value
} 

object MessageProtocol extends DefaultJsonProtocol {
  implicit val statusFormat = jsonFormat(Status)
  implicit def messageFormat[T: JsonFormat] = jsonFormat2(Message.apply[T])
}

What is best practice/approach to solve this?


Solution

  • You can simply implement your own RootJsonFormat (as an implicit in Message companion object) and override read and write functions. There you will have JsObject and you can convert it to your own case class as you want like converting the string to desired enumeration etc. You can see a sample here