如何使用Reads解析带有整数列表的JSON

时间:2013-05-28 18:30:12

标签: json scala playframework-2.0

如何在Play中构建Reads! 2.1.1读取这个JSON?下面的示例和代码抛出异常。我实际上可以在Play中运行它!控制台,但如果我启动服务器并使用curl,我会收到错误。

{
  "title": "title", 
  "description": "description", 
  "categories": [1,3], 
  "sections": [2]
}

按照游戏指南进行操作!网站让我创建了这个“解析器”,但它引发了异常。

  implicit val guideReads: Reads[GuideInstance.Update] = (
    (__ \ "title").readNullable[String] ~
    (__ \ "description").readNullable[String] ~
    (__ \ "categories").readNullable(
      Reads.list[Int]
    ) ~
    (__ \ "sections").readNullable(
      Reads.list[Int]
    )
  )(GuideInstance.Update)

异常

java.lang.NullPointerException: null
    at play.api.libs.json.Json$.fromJson(Json.scala:90) ~[play_2.10.jar:2.1.1]
    at play.api.libs.json.DefaultReads$$anon$2$$anonfun$10.apply(Reads.scala:453) ~[play_2.10.jar:2.1.1]
.......
    at play.api.libs.json.JsValue$class.validate(JsValue.scala:73) ~[play_2.10.jar:2.1.1]
    at play.api.libs.json.JsObject.validate(JsValue.scala:159) ~[play_2.10.jar:2.1.1]
    at controllers.mtadmin.GuidesController$$anonfun$update$1.apply(GuidesController.scala:114) ~[na:na]
    at controllers.mtadmin.GuidesController$$anonfun$update$1.apply(GuidesController.scala:114) ~[na:na]

1 个答案:

答案 0 :(得分:1)

使用readNullable[List[Int]]

就足够了
implicit val guideReads: Reads[GuideInstance.Update] = (
  (__ \ "title").readNullable[String] ~
  (__ \ "description").readNullable[String] ~
  (__ \ "categories").readNullable[List[Int]] ~
  (__ \ "sections").readNullable[List[Int]]
)(GuideInstance.Update)

如果没有,请提供更完整的示例,我会帮助你!