在 Scala 中解析 JSON 文件

Parsing JSON file in Scala

我有一个 JSOn 文件:

JsonString="""{"schema":{"type":"struct","name":"emp_table","fields":[{"field":"emp_id","type":"string"},{"field":"emp_name","type":"String"},{"field":"city","type":"string"},{"field":"emp_sal","type":"string"},{"field":"manager_name","type":"string"},]},"payload":{"emp_id":"1","emp_name":"abc","city":"NY","emp_sal":"100000","manager_name":"xyz"}}"""

我想解析它并将值放入 Array(1,abc,NY,100000,xyz)

我在 Scala 中使用了 Lift Json API:

case class Emp(val emp_id: String, val emp_name: String, val city: String, val emp_sal: String, val manager_name: String)

val stocks = ArrayBuffer[Emp]()
val json = JsonParser.parse(EmpString)

val elements = (json \ "payload").children
for ( acct <- elements ) {
val stock = acct.extract[Emp]
stocks += stock
}
stocks.toArray
}

但它给了我

Array[Emp] = Array(Emp(1,abc,NY,100000,xyz))

任何人都可以指导我解析这个 Json 文件或者使用任何其他 API 像 GSON 或 jackson 吗?

如果您有一个 Array[Emp],并且您想要 Array[String],您可以随时 flatMap() 它。

empArr.flatMap(_.productIterator).map(_.toString)
//res0: Array[String] = Array(1, abc, NY, 100000, xyz)