[英]Parse Jsvalue using scala
我是Scala的新手。 我有一个将其放入String的Json文件。 然后,我将字符串解析为JSValue。 现在,我试图读取所有值以更新数据库,但是我不知道如何进行。
val l = scala.io.Source.fromFile("list.json").getLines().mkString
val result: JsValue = Json.parse(l)
我的杰森就像:
{
picture_id : xxx
width : xxx
height : xxx
},
{
picture_id : xxx
width : xxx
height : xxx
},
....
我想提取甚至块来更新具有正确值的数据库。
谢谢。
您应该执行以下操作。 我希望这些评论是可以解释的:
val l = scala.io.Source.fromFile("list.json").getLines().mkString
val result: JsValue = Json.parse(l)
//Create a model to hold your json objects
case class Pic(id: String, width: String, height: String)
//Create a reader that reads your json string to your model(Pic)
implicit val picReads: Reads[Pic] = (
(JsPath \ "picture_id").read[String] and
(JsPath \ "width").read[String] and
(JsPath \ "height").read[String] and
)(Pic.apply _)
result.validate[List[Pic]] match {
case s: JsSuccess[List[Pic]] =>
//Deal with your list of pics here
case e: JsError => println("Errors: " + JsError.toFlatJson(e).toString())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.