如何在scala中解析嵌套json数组

如何在scala中解析嵌套json数组,json,scala,parsing,Json,Scala,Parsing,我有一个类似这样的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"}}] 这个解决方

我有一个类似这样的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"}}]
这个解决方案在我的情况下不起作用

var list = (jsonValue \ "certificates").as[List[Map[String,String]]]
有人能建议如何解析这个吗?

使用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 _)
你可以这样做:

  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]]
使用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 _)
你可以这样做:

  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]]

对答案稍加补充, 您必须导入以下内容才能使其正常工作:

import play.api.libs.json._ // JSON library
import play.api.libs.json.Reads._ // Custom validation helpers
import play.api.libs.functional.syntax._ // Combinator syntax
如SDK中所述:
答案的一个小补充, 您必须导入以下内容才能使其正常工作:

import play.api.libs.json._ // JSON library
import play.api.libs.json.Reads._ // Custom validation helpers
import play.api.libs.functional.syntax._ // Combinator syntax
如SDK中所述:

您正在使用哪个JSON库?我正在使用play JSON库@Yuval Ltzchakovov您正在使用哪个JSON库?我正在使用play JSON库@尤瓦尔·尔茨切科夫