Extract Options from potentially null JSON values using for expression

后端 未结 4 1756
日久生厌
日久生厌 2021-01-19 02:09

I have a JSON document where some values can be null. Using for expressions in json4s, how I can yield None, instead of nothing?

The following will fail to yield whe

4条回答
  •  离开以前
    2021-01-19 02:44

    scala> object OptExtractors {
         |
         |   // Define a custom extractor for using in for-comprehension.
         |   // It returns Some[Option[Double]], instead of Option[Double].
         |   object JDoubleOpt {
         |     def unapply(e: Any) = e match {
         |       case d: JDouble => Some(JDouble.unapply(d))
         |       case _ => Some(None)
         |     }
         |   }
         | }
    defined object OptExtractors
    
    scala>
    
    scala> val j = parse("""{
         |   "FormattedID" : "the id",
         |   "PlanEstimate" : null
         | }""")
    j: org.json4s.JValue = JObject(List((FormattedID,JString(the id)), (PlanEstimate,JNull)))
    
    scala>
    
    scala> import OptExtractors._
    import OptExtractors._
    
    scala>
    
    scala> for {
         |   JObject(list) <- j
         |   JField("FormattedID", JString(id)) <- list
         |   JField("PlanEstimate", JDoubleOpt(points)) <- list
         | } yield (id, points)
    res1: List[(String, Option[Double])] = List((the id,None))
    

提交回复
热议问题