How to represent optional fields in spray-json?

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

    Easy.

    import cc.spray.json._
    trait MyJsonProtocol extends DefaultJsonProtocol {
      implicit val searchFormat = new JsonWriter[SearchRequest] {
        def write(r: SearchRequest): JsValue = {
          JsObject(
            "url" -> JsString(r.url),
            "next_at" -> r.nextAt.toJson,
          )
        }
      }
    }
    
    class JsonTest extends FunSuite with MyJsonProtocol {
    test("JSON") {
        val search = new SearchRequest("www.site.ru", None)
        val marshalled = search.toJson
        println(marshalled)
      }
    }
    

提交回复
热议问题