json - 使用 for 表达式从可能为空的 JSON 值中提取选项

标签 json scala json4s

我有一个 JSON 文档,其中一些值可以为 null。在 json4s 中使用 for 表达式,我如何才能产生 None,而不是什么都没有?

当任一字段的值 FormattedID 时,以下将无法产生或 PlanEstimatenull .

val j: json4s.JValue = ...
for {
  JObject(list) <- j
  JField("FormattedID", JString(id)) <- list
  JField("PlanEstimate", JDouble(points)) <- list
} yield (id, points)

例如:
import org.json4s._
import org.json4s.jackson.JsonMethods._

scala> parse("""{
     |   "FormattedID" : "the id",
     |   "PlanEstimate" : null
     | }""")
res1: org.json4s.JValue = JObject(List((FormattedID,JString(the id)), 
    (PlanEstimate,JNull)))

scala> for {                                      
     | JObject(thing) <- res1                     
     | JField("FormattedID", JString(id)) <- thing
     | } yield id                                 
res2: List[String] = List(the id)

scala> for {                                      
     | JObject(thing) <- res1                     
     | JField("PlanEstimate", JDouble(points)) <- thing
     | } yield points
res3: List[Double] = List()
// Ideally res3 should be List[Option[Double]] = List(None)

最佳答案

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

关于json - 使用 for 表达式从可能为空的 JSON 值中提取选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25200005/

相关文章:

java - Jersey / jackson @JsonIgnore 上二传手

Android 小部件使用 putextra 开始新 Activity

scala - 在 chisel 中动态创建模块,同时将动态参数传递给这些模块

json - Spark + Json4s 序列化问题

java - 使用具有相同字段名称的对象的 Gson 解析 json

C#从反序列化的json对象中获取值

scala - 如何将代码块传递给函数?

scala - 为什么 print() 有副作用?

json - Spark 2.1.1 : Parsed JSON values do not match with class constructor

json - 使用JSON4S在Scala中对案例对象进行反序列化