简体   繁体   English

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

[英]how to parse nested json array in scala

i've a json like this. 我有一个像这样的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"}}]

this solution isn't working in my case. 在我的情况下,此解决方案不起作用。

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

Can some suggest how to parse this? 有人可以建议如何解析吗?

with Play JSON: 使用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]]

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 如SDK中所述: https : //www.playframework.com/documentation/2.6.x/ScalaJsonCombinators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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