【问题标题】:Spray json format for Unit typeUnit 类型的喷 json 格式
【发布时间】:2014-06-11 21:50:32
【问题描述】:

我正在编写具有以下签名的方法:

def foo[A: Marshaller, B: Marshaller](f: A => B) = {...}

问题是A 可能是Unit。有意义的是,Unit 应该有一个已经存在的 json 格式,可以在空字符串之间进行转换,而且即使这种格式不存在,实现这种格式也应该是微不足道的,这也是有道理的。我如何为 Unit 定义或导入 json 格式,就像我为案例类所做的那样:

implicit val myFormat = jsonFormat4(myCaseClassWithFourFields)

【问题讨论】:

    标签: scala spray


    【解决方案1】:

    据我所知,不存在 Unit 的预定义 json 格式。 但是你可以自己写json格式:

    import spray.json._
    import DefaultJsonProtocol._
    
    implicit object UnitJsonFormat extends JsonFormat[Unit] {
      def write(u: Unit) = JsObject()
      def read(value: JsValue): Unit = value match {
          case JsObject(fields) if fields.isEmpty => Unit
      }
    }
    

    使用它:

    scala> println("").toJson
    
    res0: spray.json.JsValue = {}
    
    scala> res0.convertTo[Unit]
    
    scala>
    

    更新:我不确定您对 Unit 的 json 有何期望,请澄清。

    【讨论】:

      【解决方案2】:

      我来到这个问题,后来发现spray为最重要的Scala Types提供JsonFormats(例如IntLongFloatDoubleByte,@ 987654330@、BigDecimalBigIntUnitBooleanCharStringSymbol) 在 trait BasicFormats

      您可以简单地混入BasicFormats,它会起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-02
        • 2015-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-23
        相关资源
        最近更新 更多