简体   繁体   中英

How to parse this JSON using Play Framework?

I have the following JSON being returned from a web service:

{
  "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": [

          ]
        }
      }
    }
  ]
}

and I am trying to parse it using the JSON parsing libs in Play Framework. I have the following code:

import play.api.libs.functional.syntax._
import play.api.libs.json._
case class Post(id: Long, date: String, count: Int)
object Post {

  implicit val postFormat = Json.format[Post]
  implicit val writes: Writes[Post] = (
    (JsPath \ "id").write[Long] and
    (JsPath \"date").write[String] and
    (JsPath \ "count").write[Int]
  )(unlift(Post.unapply))

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

import play.api.libs.json._
class PostRepo {
  val request: WSRequest = ws.url(MY_URL)

  def getPosts: Future[Seq[Post]] =
    val result: Future[JsValue] = request.get().map(response =>
        response.status match {
          case 200 => Json.parse(response.body)
          case _ => throw new Exception("Web service call failed: " + response.body)
    })
    result.map( {
        jsonvalue => println("JSARRAY: " + jsonvalue);
        (jsonvalue \ "hits").as[Seq[Post]]
    }) 
    result
}

Now, when I run the code, I am getting the following error:

 play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[JsResultException: 

JsResultException(errors:List(((0)/date,List(ValidationError(List(error.path.missing),WrappedArray()))), ((0)/count,List(ValidationError(List(error.path.missing),WrappedArray()))), ((0)/id,List(ValidationError(List(error.path.missing),WrappedArray()))), ((1)/date,List(ValidationError(List(error.path.missing),WrappedArray()))), ((1)/count,List(ValidationError(List(error.path.missing),WrappedArray()))), ((1)/id,List(ValidationError(List(error.path.missing),WrappedArray()))), ((2)/date,List(ValidationError(List(error.path.missing),WrappedArray()))), ((2)/count,List(ValidationError(List(error.path.missing),WrappedArray()))), ((2)/id,List(ValidationError(List(error.path.missing),WrappedArray()))), ((3)/date,List(ValidationError(List(error.path.missing),WrappedArray()))), ((3)/count,List(ValidationError(List(error.path.missing),WrappedArray()))), ((3)/id,List(ValidationError(List(error.path.missing),WrappedArray())))

Obviously something is wrong with the way I'm trying to parse the JSON but I have now spent a few hours trying to figure out the problem and I'm well and truly stuck.

Some refactoring code with Reads.seq

val r = (__ \ "hits").read[Seq[Post]](Reads.seq[Post])

def getPosts: Future[Seq[Post]] = {
  WS.url(MY_URL).get().map(response =>
    response.status match {
      case 200 => r.reads(response.json) match {
        case JsError(e) => throw new Exception("Json read fails. Response body:" + response.json.toString() + "\nRead error:" + e.toString())
        case JsSuccess(x, _) => x
      }
      case _ => throw new Exception("Web service call failed: " + response.body)
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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