Play Framework 2.2.2 Scala JSON读取带有未定义/空元素,导致NoSuchElementException [英] Play Framework 2.2.2 Scala JSON reads with undefined/null elements causing NoSuchElementException
问题描述
给出以下JSON数组:
Given the following JSON array:
{
"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方法实例化如下对象
Using the reads method to instanciate objects like below
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时,我会收到NoSuchElementsException(就像rotten_time一样)
I get a NoSuchElementsException when an element's value is null (like for rotten_time)
我想得到这样的东西
> 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,有没有办法确保对象实例化?我认为没有理由为每个现有字段都分配一个值.
Is there a way to ensure object instanciation even if a field value is NULL? I see no reason why every existing field has to be assigned a value to.
我在此处和
I found related questions here and here but they did not help me to solve my problem.
推荐答案
我自己找到了答案.我是Scala的新手,所以对我来说并不明显.将字段类型更改为Option [Date]解决了该问题.
I found the answer myself. I am new to Scala so it wasn't obvious for me. Changing the field type to Option[Date] solved the problem.
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
s而不是NoSuchElementException
s的一种方式.
This is a little bit unexpected as Option[] is said to be a way around NullPointerException
s but not NoSuchElementException
s.
这篇关于Play Framework 2.2.2 Scala JSON读取带有未定义/空元素,导致NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!