简体   繁体   English

Play Framework 2.2.2 Scala JSON读取带有未定义/空元素,导致NoSuchElementException

[英]Play Framework 2.2.2 Scala JSON reads with undefined/null elements causing NoSuchElementException

Given the following JSON array: 给定以下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
        }
    }
}

Using the reads method to instanciate objects like below 使用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
)

I get a NoSuchElementsException when an element's value is null (like for rotten_time) 当元素的值为null时,我会收到NoSuchElementsException(例如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? 即使字段值为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. 我在这里这里发现了相关问题,但是它们并没有帮助我解决问题。

I found the answer myself. 我自己找到了答案。 I am new to Scala so it wasn't obvious for me. 我是Scala的新手,所以对我来说并不明显。 Changing the field type to Option[Date] solved the problem. 将字段类型更改为Option [Date]解决了该问题。

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. 这有点出乎意料,因为据说Option []是解决NullPointerException而不是NoSuchElementException的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM