json - 防止 JSON4S 跳过缺少字段的 JSON 对象

标签 json scala json4s

假设我有一个像这样的简单 JSON 数组:

[ 
  { 
    "name": "Alex",
    "age": 12
  },
  { 
    "name": "Peter"
  }
]

请注意,第二个对象没有 age 字段。

我使用 JSON4S 来查询 JSON(使用 for-compressive 样式来提取值):

 for {
      JArray(persons) <- json
      JObject(person) <- persons
      JField("name", JString(name)) <- person
      JField("age", JString(age)) <- person
 } yield new Person(name, age) 

对我来说,问题是这个表达式将跳过第二个对象(缺少 age 字段的对象)。我不想跳过这些对象;我需要将其设置为 null 或更好地设置为 None


This answer给出了如何使用自定义提取器处理 JSON 中的 null 值的示例,但仅当该字段存在且其值为 null 时才有效。

最佳答案

解构 json4s 中的对象可能会带来一些不便,因为您不再可以使用花哨的 \\\ 查询。

我更喜欢做这样的事情:

for {
    JArray(persons) <- json
    person@JObject(_) <- persons
    JString(name) <- person \ "name"
    age = (person \ "age").extractOpt[Int]
     } yield (name, age)

res7: List[(String, Option[Int])] = List(("Alex", Some(12)), ("Peter", None))

此示例还说明了如何提取对象字段的两种替代方法(您也可以使用 name = (person\"name").extract[String] 代替)。

关于json - 防止 JSON4S 跳过缺少字段的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516485/

相关文章:

scala - 无法使用 Akka-Http 验证 OAuth2

json - 使用 scala 提取嵌套的 JSON 元素

json - 使用 json4s 将 scala 对象转换为 json

javascript - 使用 JSON.parse() 通过 JavaScript 忽略 JSON 中的函数

javascript - 无法使用 jQuery.parseJSON 解析 JSON 数据

scala - 从 Spark-Scala UDF 返回 Seq[Row]

json - json4s中 `render`的用途

Rails4 form_for 中的 JSON 数据类型

json - 我们如何通过网络安全地将 API key 和 secret token 交付给用户?

scala - 对象内未初始化的字段