Reputation: 1258
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
}
}
}
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
)
I get a NoSuchElementsException when an element's value is null (like for rotten_time)
I would like to get something like this
> 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)
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.
Upvotes: 2
Views: 939
Reputation: 1258
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])
So the result is
> 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)
This is a little bit unexpected as Option[] is said to be a way around NullPointerException
s but not NoSuchElementException
s.
Upvotes: 1