如何在spray-json中表示可选字段?

18

我的请求中有一个可选字段:

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

我的协议是:

object SearchRequestJsonProtocol extends DefaultJsonProtocol {
    implicit val searchRequestFormat = jsonFormat(SearchRequest, "url", "nextAt")
}

如何将nextAt字段标记为可选,以便正确读取和接受以下JSON对象:

{"url":"..."}
{"url":"...", "nextAt":null}
{"url":"...", "nextAt":"2012-05-30T15:23Z"}

实际上我并不太在乎空值的情况,但如果有细节,那就更好了。我正在使用spray-json,并且曾经认为如果在原始JSON对象中该字段不存在,使用Option将跳过该字段。

6个回答

28

对我来说可行(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")))
}

啊,我正在使用spray-json 1.0.0,Scala 2.9.0.1。我想尽快升级,但我还没有做到。谢谢你的回答! - François Beausoleil

11

你可能需要创建一个显式的格式(警告:伪代码):

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)))
        }
    }
}


0

很简单。

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)
  }
}

0
对于偶然看到此帖并想要更新 François Beausoleil 的 Spray 新版本(大约在2015年以后)答案的任何人,JsField 作为 JsValue 的公共成员已被弃用;您应该只需提供一个元组列表而不是 JsFields。他们的答案是正确的。

0

不知道这是否对您有所帮助,但您可以在Case类定义中为该字段设置默认值,因此如果该字段不在JSON中,则会将默认值分配给它。


1
那对我没用...你需要配置一些东西吗? - samthebest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接