Avinash Reddy
Avinash Reddy

Reputation: 2280

Parse json array to a case class in scala using playframework with the fields in json not matching the fields in case class

I am trying to parse a simple json array to a case class using scala and play framework. Below is the code

package com.learning.avinash.query

import play.api.libs.json.{JsPath, Json, Reads, Writes, __}
import play.api.libs.functional.syntax._

object ParseJson extends App {

  case class InfoForm(avinash: String, kranti: String, prasanth: String)

  object InfoForm {

    implicit val reads: Reads[InfoForm] = (
      (JsPath \ "username").read[String] ~
        (JsPath \ "id").read[String] ~
        (JsPath \ "full_name").read[String]
      )(InfoForm.apply _)

  }

  val json = """ {
  "data":  [
     {
      "username": "carolinabentocb",
      "id": "363753337",
      "full_name": "Carolina Bento"
    },
     {
      "username": "pereira3044",
      "id": "2141448590",
      "full_name": "Alex"
    }]
}"""

  println(Json.parse(json).as[List[InfoForm]])

}

But i am getting the following exception

Exception in thread "main" play.api.libs.json.JsResultException: JsResultException(errors:List((,List(JsonValidationError(List(error.expected.jsarray),WrappedArray())))))

Followed the below links

Parse JSON Array in Scala

Parse Json array response in scala\Play

Parse Simple Json Array in Play Framework

These link almost helped me

Stepping into JSON Arrays in Play Framework

How to parse json list or array in scala for play framework 2.2

Upvotes: 1

Views: 1479

Answers (1)

Avinash Reddy
Avinash Reddy

Reputation: 2280

Finally I could get the result of this. I have done it like this

println((Json.parse(json) \"data" ).as[List[InfoForm]])

This gives me the result

List(InfoForm(carolinabentocb,363753337,Carolina Bento), InfoForm(pereira3044,2141448590,Alex))

Upvotes: 3

Related Questions