JSON not being parsed correctly by Play Framework

我怕爱的太早我们不能终老 提交于 2019-12-24 17:27:57

问题


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 _)
}

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?


回答1:


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

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.




回答2:


You shouldn't define a Format[HiringPost] if you have a Reads and a Writes. I'm surprised that's not an implicit resolution error. Get rid of this line:

implicit val hiringPostFormat = Json.format[HiringPost]

You can also replace your trivial Writes implicitation with the macro Json.writes[HiringPost]



来源:https://stackoverflow.com/questions/35655592/json-not-being-parsed-correctly-by-play-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!