Play框架无法正确解析JSON [英] JSON not being parsed correctly by Play Framework

查看:134
本文介绍了Play框架无法正确解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,用于尝试将JSON解析为Scala case类:

I have the following code which I'm using to try and parse some JSON into a Scala case class:

 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)

还有一些隐式代码可以在此处进行转换:

And some implicits to do the conversion here:

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时得到的响应是:

but the response I am getting when trying to parse the JSON is:

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())))))

我编写解析或隐式方法有什么问题?

what is wrong with the way I have written the parsing or implicits?

推荐答案

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

If you're using Reads and Writes you don't need Formats.

删除您的implicit val hiringPostFormat = Json.format[HiringPost]并在解析类中添加import HiringPost._,以将隐式对象放到作用域中-它将起作用.

Remove your implicit val hiringPostFormat = Json.format[HiringPost] and add import HiringPost._ in your parsing class to put the implicits in scope - it will work.

这篇关于Play框架无法正确解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆