Play Framework未正确解析JSON

时间:2016-02-26 15:27:33

标签: json scala playframework playframework-2.0

我有以下代码,我正在尝试将一些JSON解析为Scala案例类:

 val json =
    """{"hits": [
        {"created_at":"2016-02-01T15:01:03.000Z","title":"title","num_comments":778,"parent_id":null,"_tags":["story","author","story_11012044"],"objectID":"11012044","_highlightResult":{"title":{"value":"title","matchLevel":"full","matchedWords":["title"]},"author":{"value":"author","matchLevel":"none","matchedWords":[]},"story_text":{"value":"Please lead","matchLevel":"none","matchedWords":[]}}}
    ]}""".stripMargin

  val jsobj = Json.parse(json)
  val r = (JsPath \ "hits").read[Seq[HiringPost]](Reads.seq[HiringPost])
  val res: JsResult[Seq[HiringPost]] = r.reads(jsobj)
  println("result is: " + res)

这里有一些暗示进行转换:

case class HiringPost(date: String, count: Int, id: String )
object HiringPost {

  implicit val hiringPostFormat = Json.format[HiringPost]

  implicit val hiringWrites: Writes[HiringPost] = (
    (JsPath \ "date").write[String] and
    (JsPath \ "count").write[Int] and
    (JsPath \ "id").write[String]
  )(unlift(HiringPost.unapply))

  implicit val hiringReads: Reads[HiringPost] = (
    (JsPath \  "created_at").read[String] and
    (JsPath \  "num_comments").read[Int] and
    (JsPath \  "objectID").read[String]
  )(HiringPost.apply _)
}

但是我在尝试解析JSON时得到的响应是:

result is: JsError(List((/hits(0)/date,List(ValidationError(List(error.path.missing),WrappedArray()))), (/hits(0)/count,List(ValidationError(List(error.path.missing),WrappedArray()))), (/hits(0)/id,List(ValidationError(List(error.path.missing),WrappedArray())))))

我编写解析或暗示的方式出了什么问题?

2 个答案:

答案 0 :(得分:1)

如果您有“读取”和“写入”,则不应定义Format[HiringPost]。我很惊讶这不是一个隐含的解决方案错误。摆脱这一行:

implicit val hiringPostFormat = Json.format[HiringPost]

您还可以使用宏Json.writes[HiringPost]

替换您的琐碎写作隐含

答案 1 :(得分:1)

如果您使用ReadsWrites,则不需要Formats

删除您的implicit val hiringPostFormat = Json.format[HiringPost]并在解析类中添加import HiringPost._以将隐含内容放在范围内 - 它会起作用。