如何在spray-json中表示可选字段? [英] How to represent optional fields in spray-json?

查看:116
本文介绍了如何在spray-json中表示可选字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an optional field on my requests:

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

我的协议是:

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

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

How do I mark the nextAt field optional, such that the following JSON objects will be correctly read and accepted:

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

我实际上并不十分在意null大小写,但是如果您有详细信息,那会很好.我正在使用spray-json,给人的印象是,如果原始JSON对象上没有该字段,则使用Option会跳过该字段.

I actually don't really care about the null case, but if you have details, it would be nice. I'm using spray-json, and was under the impression that using an Option would skip the field if it was absent on the original JSON object.

推荐答案

您可能必须创建一个显式格式(警告:psuedocodish):

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

这篇关于如何在spray-json中表示可选字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆