【问题标题】:Prevent JSON4S from skipping JSON objects with a missing field防止 JSON4S 跳过缺少字段的 JSON 对象
【发布时间】:2016-02-19 22:45:42
【问题描述】:

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

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

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

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

 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 时才有效。

【问题讨论】:

    标签: json scala json4s


    【解决方案1】:

    在 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])。

    【讨论】:

      猜你喜欢
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2011-08-18
      相关资源
      最近更新 更多