How to represent optional fields in spray-json?

前端 未结 6 994
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 06:36

I have an optional field on my requests:

case class SearchRequest(url: String, nextAt: Option[Date])

My protocol is:

object Sea         


        
6条回答
  •  攒了一身酷
    2021-02-07 07:30

    You might have to create an explicit format (warning: psuedocodish):

    object SearchRequestJsonProtocol extends DefaultJsonProtocol {
        implicit object SearchRequestJsonFormat extends JsonFormat[SearchRequest] {
            def read(value: JsValue) = value match {
                case JsObject(List(
                        JsField("url", JsString(url)),
                        JsField("nextAt", JsString(nextAt)))) =>
                    SearchRequest(url, Some(new Instant(nextAt)))
    
                case JsObject(List(JsField("url", JsString(url)))) =>
                    SearchRequest(url, None)
    
                case _ =>
                    throw new DeserializationException("SearchRequest expected")
            }
    
            def write(obj: SearchRequest) = obj.nextAt match {
                case Some(nextAt) => 
                    JsObject(JsField("url", JsString(obj.url)),
                             JsField("nextAt", JsString(nextAt.toString)))
                case None => JsObject(JsField("url", JsString(obj.url)))
            }
        }
    }
    

提交回复
热议问题