How to represent optional fields in spray-json?

前端 未结 6 997
伪装坚强ぢ
伪装坚强ぢ 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:22

    Works for me (spray-json 1.1.1 scala 2.9.1 build)

    import cc.spray.json._
    import cc.spray.json.DefaultJsonProtocol._
    
    // string instead of date for simplicity
    case class SearchRequest(url: String, nextAt: Option[String])
    
    // btw, you could use jsonFormat2 method here
    implicit val searchRequestFormat = jsonFormat(SearchRequest, "url", "nextAt")
    
    assert {
      List(
        """{"url":"..."}""",
        """{"url":"...", "nextAt":null}""",
        """{"url":"...", "nextAt":"2012-05-30T15:23Z"}""")
      .map(_.asJson.convertTo[SearchRequest]) == List(
        SearchRequest("...", None),
        SearchRequest("...", None),
        SearchRequest("...", Some("2012-05-30T15:23Z")))
    }
    

提交回复
热议问题