2016-05-02 95 views
1

如何訪問第一個居民的名字?這是Json文件。以下是什麼?在斯卡拉閱讀JsValue

val bigwig = (json \ "residents")(1)..... 


import play.api.libs.json._ 

val json: JsValue = Json.parse(""" 
{ 
    "name" : "Watership Down", 
    "location" : { 
    "lat" : 51.235685, 
    "long" : -1.309197 
    }, 
    "residents" : [ { 
    "name" : "Fiver", 
    "age" : 4, 
    "role" : null 
    }, { 
    "name" : "Bigwig", 
    "age" : 6, 
    "role" : "Owsla" 
    } ] 
} 
""") 

回答

0

你可以通過幾種方法做到這一點。類映射和直接JSON字段訪問的

例子

import play.api.libs.json.{JsError, JsSuccess, Json} 

case class JsonSchemaView(name: String, location: Location, residents: Seq[Resident]) 

case class Location(lat: Double, long: Double) 

case class Resident(name: String, age: Int, role: Option[String]) 

object Location { 
    implicit val locationFormat = Json.format[Location] 
} 

object Resident { 
    implicit val residentFormat = Json.format[Resident] 
} 

object JsonSchemaView { 
    implicit val jsonSchemaViewFormat = Json.format[JsonSchemaView] 
} 

object Runner { 
    def main (args: Array[String]) { 

    val mySchemaView = JsonSchemaView("name", Location(40, -40), Seq(Resident("ress", 4, None), Resident("josh", 16, Option("teenager")))) 

    val json = Json.toJson(mySchemaView) 

    println(Json.prettyPrint(json)) 

    val myParsedSchema = Json.parse(json.toString).validate[JsonSchemaView] 

    myParsedSchema match { 
     case JsSuccess(schemaView, _) => 
     println(s"success: $schemaView") 
     case error: JsError => 
     println(error) 
    } 


    //The hard way 
    val jsonObject = Json.parse(json.toString()) 

    (jsonObject \ "name").validate[String] match { 
     case JsSuccess(name, _) => 
     println(s"success: $name") 
     case error: JsError => 
     println(error) 
    } 

    (jsonObject \ "residents").validate[Seq[JsObject]] match { 
     case JsSuccess(residents, _) => 
     residents foreach { resident => 
      println((resident \ "age").as[Int]) //unsafe, using the wrong type will cause an exception 
     } 
     case error: JsError => 
     println(error) 
     } 
    } 
} 
3

快速和骯髒的(無驗證):

((jsonObject \ "residents").as[Seq[JsObject]].head \ "name").as[String] 
0

你的代碼的一部分返回JSON,所以你可以使用所有的JSON方法from JSON basics

For access name field use path:(...\"name)"

獲取名稱值使用as方法:(...\"name").as[String]