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