给出以下JSON数组:
{
"success": true,
"data": [
{
"id": 600,
"stage_id": 15,
"title": "test deal",
"value": 0,
"currency": "EUR",
"rotten_time": "2014-03-18 17:45:51",
},
{
"id": 601,
"stage_id": 15,
"title": "test deal2 deal",
"value": 0,
"currency": "EUR",
"rotten_time": "2014-03-24 14:11:00"
},
{
"id": 602,
"stage_id": 15,
"title": "test deal2 deal",
"value": 0,
"currency": "EUR",
"rotten_time": null
}
],
"additional_data": {
"pagination": {
"start": 0,
"limit": 100,
"more_items_in_collection": false
}
}
}
使用reads方法实现如下所示的对象
case class Deal(id: Long, stage_id: Long, status: String, rotten_time: Date)
implicit val dealReader = Json.reads[Deal]
val futureJson: Future[List[Deal]] = futureResponse.map(
response => (response.json \ "data").validate[List[Deal]].get
)
当元素的值为null时(比如rotten_time),我得到NoSuchElementsException
我想得到类似的东西
> println(deals.toString)
> Deal(601,15,open,Mon Mar 18 17:45:51 CET 2014)
> Deal(602,15,open,Mon Mar 18 14:11:00 CET 2014)
> Deal(603,15,open,null)
即使字段值为NULL,有没有办法确保对象实例化?我认为没有必要为每个现有字段分配值。
答案 0 :(得分:1)
我自己找到了答案。我是Scala的新手,所以对我来说并不明显。将字段类型更改为Option [Date]可解决问题。
case class Deal(id: Long, stage_id: Long, status: String, rotten_time: Option[Date])
结果是
> println(deals.toString)
> Deal(601,15,open,Some(Mon Mar 18 17:45:51 CET 2014))
> Deal(602,15,open,Some(Mon Mar 18 14:11:00 CET 2014))
> Deal(603,15,open,None)
这有点出乎意料,因为Option []被称为绕NullPointerException
而不是NoSuchElementException
的方式。