【问题标题】:Play Framework 2.2.2 Scala JSON reads with undefined/null elements causing NoSuchElementExceptionPlay Framework 2.2.2 Scala JSON 读取未定义/空元素导致 NoSuchElementException
【发布时间】:2014-03-31 09:09:01
【问题描述】:

给定以下 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,是否有办法确保对象实例化?我认为没有理由必须为每个现有字段分配一个值。

我找到了相关问题herehere,但它们并没有帮助我解决我的问题。

【问题讨论】:

    标签: json scala playframework


    【解决方案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[] 可以绕过NullPointerExceptions 而不是NoSuchElementExceptions。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多