问题描述
我有以下代码,用于尝试将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?
推荐答案
如果您使用的是Reads
和Writes
,则不需要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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!