2016-02-19 24 views
1

讓我們假設我有一個簡單的JSON數組是這樣的:防止JSON4S從跳過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

回答

2

解析json4s中的對象可能會帶來一些不便,因爲您不再使用花式的\\\查詢。

我喜歡做這樣的事情:

for { 
    JArray(persons) <- json 
    [email protected](_) <- 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]代替)。