1

i've a json like this.

certificates: [{type: "abc",file: {name: "xyz",path:"/usr/local",extension: "csv"}} ,  {type: "xyz",file: {name: "xyz",path: "/usr/local",extension: "csv"}} , {type: "nmo",file: {name: "xyz",path: "/usr/local",extension: "csv"}}]

this solution isn't working in my case.

var list = (jsonValue \ "certificates").as[List[Map[String,String]]]

Can some suggest how to parse this?

2
  • Which JSON library are you using? Commented Feb 11, 2016 at 7:20
  • i am using play json library. @Yuval ltzchakov Commented Feb 11, 2016 at 13:40

2 Answers 2

3

with Play JSON:

case class CertFile(name: String, path: String, extension: String)

case class Certificate(certType: String, certFile: CertFile)


implicit val certFile: Reads[CertFile] = (
    (JsPath \ "name").read[String] and
      (JsPath \ "path").read[String] and
      (JsPath \ "extension").read[String]
    ) (CertFile.apply _)

  implicit val cert: Reads[Certificate] = (
    (JsPath \ "type").read[String] and
      (JsPath \ "file").read[CertFile]
    ) (Certificate.apply _)

and you can use this way:

  val json =
    """{ "certificates": [{"type": "abc","file": {"name": "xyz","path":"/usr/local","extension": "csv"}} ,  {"type": "xyz","file": {"name": "xyz","path": "/usr/local","extension": "csv"}} , {"type": "nmo","file": {"name": "xyz","path": "/usr/local","extension": "csv"}}] }"""

  val jsonValue = Json.parse(json)

  val list = (jsonValue \ "certificates").as[List[Certificate]]
Sign up to request clarification or add additional context in comments.

Comments

1

A small addition to the answer, You'll have to import the following to get this to work:

import play.api.libs.json._ // JSON library
import play.api.libs.json.Reads._ // Custom validation helpers
import play.api.libs.functional.syntax._ // Combinator syntax

As mentioned in the SDK: https://www.playframework.com/documentation/2.6.x/ScalaJsonCombinators

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.