简体   繁体   English

如何使用读取来解析带有整数列表的JSON

[英]How do I parse JSON with a list of integers using Reads

How do I construct a Reads in Play! 我该如何构建阅读游戏! 2.1.1 which reads this JSON? 2.1.1哪个读取此JSON? The example and code below throws an exception. 下面的示例和代码引发异常。 I can actually run it in the Play! 我实际上可以在Play中运行它! console, but if I start the server and use curl I get an error. 控制台,但是如果我启动服务器并使用curl,则会出现错误。

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

Following the guide on Play! 遵循Play指南! website made me create this "parser", but it throws an exception. 网站让我创建了这个“解析器”,但引发了异常。

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

Exception 例外

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]

It should suffice to use readNullable[List[Int]] 使用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)

If it doesn't please provide a more complete example and I will help you out! 如果没有,请提供更完整的示例,我将为您提供帮助!

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

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