[英]Convert JSON object to List<>
我想將 JSON object 轉換為不同的格式。 我的 JSON object 看起來像。
{
"schema": [
{
"name": "cust_id",
"data_type": "String",
"nullable": true
},
{
"name": "source_type",
"data_type": "String",
"nullable": true
}
]
}
我想要下面的 output:
val colType = List(("cust_id","String",true),("source_type","String",true))
我想要 Scala 中的轉換。
使用Circe怎么樣?
import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
import cats.syntax.show._
case class Schema(schema: List[Container])
case class Container(name:String, data_type: String, nullable: Boolean)
val json = """
{
"schema": [{
"name": "cust_id",
"data_type": "String",
"nullable": true
},
{
"name": "source_type",
"data_type": "String",
"nullable": true
}
]
}"""
decode[Schema](json) match {
case Right(result) => println(result.schema.map{case Container(a,b,c) => (a,b,c)})
case Left(failure) => println(failure.show)
}
您也可以使用 spray.json。
在 build.sbt 中添加依賴
libraryDependencies += "io.spray" %% "spray-json" % "1.3.6"
應用:
import spray.json._
//create your model classes
case class MyItem(name: String, data_type: String, nullable: Boolean)
case class MySchema(schema: Seq[MyItem])
//prepare JSON protocol
trait MyJsonProtocol extends DefaultJsonProtocol {
//MyItem has 3 fields, so you have to use jsonFormat3
implicit val myItemFormat: RootJsonFormat[MyItem] = jsonFormat3(MyItem)
//MySchema has 1 field, so you have to use jsonFormat1
implicit val mySchemaFormat: RootJsonFormat[MySchema] = jsonFormat1(MySchema)
}
//extends your application with your JSON protocol
object MyApplication extends App with MyJsonProtocol {
val json =
"""{
|"schema": [{
| "name": "cust_id",
| "data_type": "String",
| "nullable": true
| },
| {
| "name": "source_type",
| "data_type": "String",
| "nullable": true
| }
|]
|}""".stripMargin
//execute parsing
val parsed = json.parseJson.convertTo[MySchema]
//true
println(parsed.schema == List(MyItem("cust_id","String",true), MyItem("source_type","String",true)))
}
我將演示如何使用play-json來實現。 如果您想將其序列化為案例 class,如其他答案中所示,您可以定義類及其序列化程序:
case class Schema(name: String, data_type: String, nullable: Boolean)
object Schema {
implicit val format: OFormat[Schema] = Json.format[Schema]
}
case class Schemas(schema: Seq[Schema])
object Schemas {
implicit val format: OFormat[Schemas] = Json.format[Schemas]
}
然后只需調用:
println(Json.parse(jsonString).as[Schemas])
代碼在Scastie運行。
但如果你真的想要元組列表,你可以這樣做:
val path = JsPath \ "schema"
val schemas = path(Json.parse(jsonString)) match {
case List(arr) =>
arr match {
case arr: JsArray =>
arr.value.map(_.validate[JsObject] match {
case JsSuccess(value, _) =>
value.values.toList match {
case List(a, b, c) =>
(a, b, c)
case _ => ???
}
case JsError(errors) =>
??? // Error handling
}).toList
case _ => ??? // Error handling
}
case _ => ??? // Error handling
}
在Scastie運行的代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.